<?xml version="1.0" encoding="UTF-8"?>
<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:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" 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 MathWorks. She writes here about once a week on MATLAB programming and related topics.</description>
	<lastBuildDate>Sat, 04 May 2013 14:47:31 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/mathworks/loren" /><feedburner:info uri="mathworks/loren" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Recent Question about Speed with Subarray Calculations</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/9te7pV1k6Q4/</link>
		<comments>http://blogs.mathworks.com/loren/2013/05/04/recent-question-about-speed-with-subarray-calculations/#comments</comments>
		<pubDate>Sat, 04 May 2013 14:47:31 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Best Practice]]></category>
		<category><![CDATA[Efficiency]]></category>
		<category><![CDATA[Puzzles]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=688</guid>
		<description><![CDATA[Recently someone asked me to explain the speed behavior doing a calculation using a loop and array indexing vs. getting the subarray first.ContentsExampleFirst MethodSecond MethodSame Results?Compare RuntimeWhat's Happening?Your Results?ExampleSuppose I have a function of two inputs, the first input being the column (of a square array), the second, a scalar, and the output, a vector.myfun [...]]]></description>
				<content:encoded><![CDATA[
<div class="content"><!--introduction--><p>Recently someone asked me to explain the speed behavior doing a calculation using a loop and array indexing vs. getting the subarray first.</p><!--/introduction--><h3>Contents</h3><div><ul><li><a href="#993880b3-5843-4778-bc94-32d83ac85cac">Example</a></li><li><a href="#6af5b04d-a4a2-4d87-87e3-80b5f5e558e1">First Method</a></li><li><a href="#268c5a14-73fe-439d-8a70-9c107435afbe">Second Method</a></li><li><a href="#9ccb7a79-b332-4e32-abe0-81a3ed286deb">Same Results?</a></li><li><a href="#6ae5ef22-d2db-4d73-9f37-b3d80d85f82d">Compare Runtime</a></li><li><a href="#aea57373-3b4c-4692-ad92-ac8c6dfe920c">What's Happening?</a></li><li><a href="#b2f25522-87bc-4cc4-a85d-00bc6f60d4fc">Your Results?</a></li></ul></div><h4>Example<a name="993880b3-5843-4778-bc94-32d83ac85cac"></a></h4><p>Suppose I have a function of two inputs, the first input being the column (of a square array), the second, a scalar, and the output, a vector.</p><pre class="codeinput">myfun = @(x,z) x'*x+z;
</pre><p>And even though this may be calculated in a fully vectorized manner, let's explore what happens when we work on subarrays from the array input.</p><p>I am now creating the input array <tt>x</tt> and the results output arrays for doing the calculation two ways, with an additional intermediate step in one of the methods.</p><pre class="codeinput">n = 500;
x = randn(n,n);
result1 = zeros(n,1);
result2 = zeros(n,1);
</pre><h4>First Method<a name="6af5b04d-a4a2-4d87-87e3-80b5f5e558e1"></a></h4><p>Here we see and time the first method.  In this one, we create a temporary array for <tt>x(:,k)</tt> <tt>n</tt> times through the outer loop.</p><pre class="codeinput">tic
<span class="keyword">for</span> k = 1:n
    <span class="keyword">for</span> z = 1:n
        result1(z) = myfun(x(:,k), z);
    <span class="keyword">end</span>
    result1 = result1+x(:,k);
<span class="keyword">end</span>
runtime(1) = toc;
</pre><h4>Second Method<a name="268c5a14-73fe-439d-8a70-9c107435afbe"></a></h4><p>In this method, we extract the column of interest first in the outer loop, and reuse that temporary array each time through the inner loop. Again we see and time the results.</p><pre class="codeinput">tic
<span class="keyword">for</span> k = 1:n
    xt = x(:,k);
    <span class="keyword">for</span> z = 1:n
        result2(z) = myfun(xt, z);
    <span class="keyword">end</span>
    result2 = result2+x(:,k);
<span class="keyword">end</span>
runtime(2) = toc;
</pre><h4>Same Results?<a name="9ccb7a79-b332-4e32-abe0-81a3ed286deb"></a></h4><p>First, let's make sure we get the same answer both ways.  You can see that we do.</p><pre class="codeinput">theSame = isequal(result1,result2)
</pre><pre class="codeoutput">theSame =
     1
</pre><h4>Compare Runtime<a name="6ae5ef22-d2db-4d73-9f37-b3d80d85f82d"></a></h4><p>Next, let's compare the times.  I want to remind you that doing timing from a script generally has more overhead than when the same code is run inside a function.  We just want to see the relative behavior so we should get some insight from this exercise.</p><pre class="codeinput">disp([<span class="string">'Run times are: '</span>,num2str(runtime)])
</pre><pre class="codeoutput">Run times are: 2.3936      1.9558
</pre><h4>What's Happening?<a name="aea57373-3b4c-4692-ad92-ac8c6dfe920c"></a></h4><p>Here's what's going on.  In the first method, we create a temporary variable <tt>n</tt> times through the outer loop, even though that array is a constant for a fixed column.  In the second method, we extract the relevant column once, and reuse it <tt>n</tt> times through the inner loop.</p><p>Be thoughtful if you do play around with this.  Depending on the details of your function, if the calculations you do each time are large compared to the time to extract a column vector, you may not see much difference between the two methods.  However, if the calculations are sufficiently short in duration, then the repeated creation of the temporary variable could add a tremendous amount of overhead to the calculation.  In general, you should not be worse off always capturing the temporary array the fewest number of times possible.</p><h4>Your Results?<a name="b2f25522-87bc-4cc4-a85d-00bc6f60d4fc"></a></h4><p>Have you noticed similar timing "puzzles" when analyzing one of your algorithms?  I'd love to hear more <a href="http://blogs.mathworks.com/loren/?p=688#respond">here</a>.</p><script language="JavaScript"> <!-- 
    function grabCode_97656ef0fbe04d9386fa579d56ff2ea6() {
        // 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='97656ef0fbe04d9386fa579d56ff2ea6 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 97656ef0fbe04d9386fa579d56ff2ea6';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_97656ef0fbe04d9386fa579d56ff2ea6()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><!--
97656ef0fbe04d9386fa579d56ff2ea6 ##### SOURCE BEGIN #####
%% Recent Question about Speed with Subarray Calculations
% Recently someone asked me to explain the speed behavior doing a
% calculation using a loop and array indexing vs. getting the subarray
% first.
%% Example
% Suppose I have a function of two inputs, the first input being the column
% (of a square array), the second, a scalar, and the output, a vector. 
myfun = @(x,z) x'*x+z;

%%
% And even though this may be calculated in a fully vectorized manner,
% let's explore what happens when we work on subarrays from the array
% input.
%%
% I am now creating the input array |x| and the results output arrays for
% doing the calculation two ways, with an additional intermediate step in
% one of the methods.
n = 500;
x = randn(n,n);
result1 = zeros(n,1);
result2 = zeros(n,1);
%% First Method
% Here we see and time the first method.  In this one, we create a
% temporary array for |x(:,k)| |n| times through the outer loop.
tic
for k = 1:n
    for z = 1:n
        result1(z) = myfun(x(:,k), z);
    end
    result1 = result1+x(:,k);
end
runtime(1) = toc;

%% Second Method
% In this method, we extract the column of interest first in the outer
% loop, and reuse that temporary array each time through the inner loop.
% Again we see and time the results.
tic
for k = 1:n
    xt = x(:,k);
    for z = 1:n
        result2(z) = myfun(xt, z);
    end
    result2 = result2+x(:,k);
end
runtime(2) = toc;
%% Same Results?
% First, let's make sure we get the same answer both ways.  You can see
% that we do.
theSame = isequal(result1,result2)

%% Compare Runtime
% Next, let's compare the times.  I want to remind you that doing timing
% from a script generally has more overhead than when the same code is run
% inside a function.  We just want to see the relative behavior so we
% should get some insight from this exercise.
disp(['Run times are: ',num2str(runtime)])
%% What's Happening?
% Here's what's going on.  In the first method, we create a temporary
% variable |n| times through the outer loop, even though that array is a
% constant for a fixed column.  In the second method, we extract the
% relevant column once, and reuse it |n| times through the inner loop.
%
% Be thoughtful if you do play around with this.  Depending on the details
% of your function, if the calculations you do each time are large compared
% to the time to extract a column vector, you may not see much difference
% between the two methods.  However, if the calculations are sufficiently
% short in duration, then the repeated creation of the temporary variable
% could add a tremendous amount of overhead to the calculation.  In
% general, you should not be worse off always capturing the temporary array
% the fewest number of times possible.
%% Your Results?
% Have you noticed similar timing "puzzles" when analyzing one of your
% algorithms?  I'd love to hear more
% <http://blogs.mathworks.com/loren/?p=688#respond here>.

##### SOURCE END ##### 97656ef0fbe04d9386fa579d56ff2ea6
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/9te7pV1k6Q4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/05/04/recent-question-about-speed-with-subarray-calculations/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/05/04/recent-question-about-speed-with-subarray-calculations/</feedburner:origLink></item>
		<item>
		<title>Using Symbolic Math Toolbox to Compute Area Moments of Inertia</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/GAkkzQGU4nE/</link>
		<comments>http://blogs.mathworks.com/loren/2013/04/26/using-symbolic-math-toolbox-to-compute-area-moments-of-inertia/#comments</comments>
		<pubDate>Fri, 26 Apr 2013 11:14:21 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Symbolic]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=684</guid>
		<description><![CDATA[Once more I am pleased to introduce guest blogger Kai Gehrs. Kai has been a Software Engineer at MathWorks for the past five years working on the Symbolic Math Toolbox. He has a background in mathematics and computer science. He already contributed to my BLOG in the past writing about Using Symbolic Equations And Symbolic [...]]]></description>
				<content:encoded><![CDATA[
<div class="content"><!--introduction--><p>Once more I am pleased to introduce guest blogger Kai Gehrs. Kai has been a Software Engineer at MathWorks for the past five years working on the <a href="http://www.mathworks.com/help/toolbox/symbolic">Symbolic Math Toolbox</a>. He has a background in mathematics and computer science. He already contributed to my BLOG in the past writing about <a href="http://blogs.mathworks.com/loren/2012/07/27/using-symbolic-equations-and-symbolic-functions-in-matlab">Using Symbolic Equations And Symbolic Functions In MATLAB</a> as well as on approaches for <a href="http://blogs.mathworks.com/loren/2011/10/25/simplifying-symbolic-results">Simplifying Symbolic Results</a>.</p><!--/introduction--><h3>Contents</h3><div><ul><li><a href="#05e69b68-4591-4e86-a7a3-4366fbda2fad">In a Nutshell: What Is This Article About?</a></li><li><a href="#510e5d8c-2254-4f99-9565-cc9fb1f1338c">Basic Example: Cross Section of an Elliptical Tube</a></li><li><a href="#319f5ba4-64a6-4e2e-b648-831a0818d6ff">Area Moment Of Inertia</a></li><li><a href="#3b715d35-70da-4013-bb0b-470df2df3da5">Math Behind This Example</a></li><li><a href="#19841dd9-5c50-4448-ba67-76dd636545d3">Symbolic Integration</a></li><li><a href="#6c55693e-8593-48c1-90be-48129f5b3b0e">Advanced Example: Cross Section of an Elliptical Tube Defined by Symbolic Parameters</a></li><li><a href="#2415b2ac-5410-444a-8c2b-f15693021763">How to Create MuPAD Graphics Shown in This Article</a></li><li><a href="#ebec3076-fed9-49e8-967d-2c5a6a31fea0">Have You Tried Symbolic Math Toolbox?</a></li></ul></div><h4>In a Nutshell: What Is This Article About?<a name="05e69b68-4591-4e86-a7a3-4366fbda2fad"></a></h4><p>If you are interested in using MATLAB and the Symbolic Math Toolbox in teaching some basics in mechanical engineering, this might be of interest to you.</p><p>Computing <i>area moments of inertia</i> is an important task in mechanics. For example, area moments of inertia play a critical role in stress, dynamic, and stability analysis of structures. In this article, we use capabilities of the <a href="www.mathworks.com/products/symbolic">Symbolic Math Toolbox</a> to compute area moments for cross sections of elliptical tubes.</p><p>We start with a basic case involving only numeric parameters, and then make the computations more general by introducing symbolic parameters.</p><p>All plots used in this article have been created in the <a href="http://www.mathworks.de/discovery/mupad.html">MuPAD Notebook app</a>. You can find the source code for these plots at the end of the article.</p><h4>Basic Example: Cross Section of an Elliptical Tube<a name="510e5d8c-2254-4f99-9565-cc9fb1f1338c"></a></h4><p>The following picture shows the cross section of an elliptical tube.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/lateralCut.png" alt=""> </p><p>The following ellipses define outer and inner contours of the section:</p><div><ul><li>$y = \pm 2 \, \sqrt{1 - \frac{x^2}{9}}$ describe the <i>outer</i> contour line for $x \in [-3,3]$.</li><li>$y = \pm \sqrt{1 - \frac{x^2}{4}}$ describe the <i>inner</i> contour line for $x \in [-2,2]$.</li></ul></div><p>We will compute the area moment of inertia of this section with respect to the $x$-axis.</p><h4>Area Moment Of Inertia<a name="319f5ba4-64a6-4e2e-b648-831a0818d6ff"></a></h4><p>The moment of inertia of an area $A$ with respect to the $x$-axis is defined in terms of the double integral</p><p>$$I_x = {\int \int}_A y^2\, \mathrm{d}A.$$</p><p>You can find this definition on <a href="http://en.wikipedia.org/wiki/Second_moment_of_area">Wikipedia</a>.</p><h4>Math Behind This Example<a name="3b715d35-70da-4013-bb0b-470df2df3da5"></a></h4><p>In our example, the area $A$ is the hatched area shown in the previous plot. Taking advantage of the symmetry of the section with respect to both the $x$- and $y$-axes, we can restrict our computations to the first quadrant of the $x-y$-plane.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/UpperQuarterLateralCut.png" alt=""> </p><p>To compute the necessary double integral over the hatched area, we divide this area into two separate areas $A1$ and $A2$.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/IntegrationAreas.png" alt=""> </p><p>To compute the final area moment of inertia about the x-axis, we multiply the sum of the double integrals over $A_1$ and $A_2$ by four.</p><p>$$I_x = {\int\int}_A y^2 \, \mathrm dA = 4 \cdot \Big({\int\int}_{A_1}
y^2 \, \mathrm dA_1 + {\int\int}_{A_2} y^2 \, \mathrm dA_2\Big).$$</p><p>Now, we only need to compute these two double integrals. The mathematical theory behind multi-dimensional integration tells us that we can rewrite each of these double integrals in terms of two integrals:</p><p>$$I_1 = {\int\int}_{A_1} y^2 \, \mathrm dA_1 = \int_0^2 \int_{\sqrt{1 -
\frac{x^2}{4}}}^{2 \, \sqrt{1 - \frac{x^2}{9}}} y^2 \, \mathrm dy \,
\mathrm dx,$$</p><p>$$I_2 = {\int\int}_{A_2} y^2 \, \mathrm dA_2 = \int_2^3 \int_{0}^{2 \, \sqrt{1 - \frac{x^2}{9}}}
y^2\, \mathrm dy\, \mathrm dx.$$</p><p>The <a href="http://www.mathworks.com/help/toolbox/symbolic/int.html"><tt>int</tt></a> function from the Symbolic Math Toolbox can compute these integrals.</p><h4>Symbolic Integration<a name="19841dd9-5c50-4448-ba67-76dd636545d3"></a></h4><p>We define $x$ and $y$ as symbolic variables:</p><pre class="codeinput">syms <span class="string">x</span> <span class="string">y</span>;
</pre><p>We start computing the inner integral $\int_{\sqrt{1 - \frac{x^2}{4}}}^{2 \, \sqrt{1 - \frac{x^2}{9}}} y^2 \, \mathrm dy$ of $I_1$:</p><pre class="codeinput">innerI1 = int(y^2, y, sqrt(1-x^2/4), 2*sqrt(1-x^2/9))
</pre><pre class="codeoutput">innerI1 =
(8*(9 - x^2)^(3/2))/81 - (4 - x^2)^(3/2)/24
</pre><p>Next, we integrate <tt>innerI1</tt> with respect to $x$ from $0$ to $2$. This provides $I_1$:</p><pre class="codeinput">I1 = int(innerI1, x, 0, 2)
</pre><pre class="codeoutput">I1 =
3*asin(2/3) - pi/8 + (74*5^(1/2))/81
</pre><p>We use the same strategy to compute $I_2$. First, we compute the inner integral $\int_{0}^{2 \, \sqrt{1 - \frac{x^2}{9}}} y^2\, \mathrm dy$. Then, we integrate the resulting expression with respect to $x$ from $2$ to $3$:</p><pre class="codeinput">I2 = int(int(y^2, y, 0, 2*sqrt(1-x^2/9)), x, 2, 3);
</pre><p>Hence, the area moment of inertia of the elliptical tube with respect to the $x$-axis is</p><pre class="codeinput">Ix = 4 * (I1 + I2)
</pre><pre class="codeoutput">Ix =
(11*pi)/2
</pre><p>We can approximate the result numerically by using the <a href="http://www.mathworks.com/help/toolbox/symbolic/vpa.html"><tt>vpa</tt></a> function. For example, we approximate the result using 5 significant (nonzero) digits:</p><pre class="codeinput">vpa(Ix, 5)
</pre><pre class="codeoutput">ans =
17.279
</pre><h4>Advanced Example: Cross Section of an Elliptical Tube Defined by Symbolic Parameters<a name="6c55693e-8593-48c1-90be-48129f5b3b0e"></a></h4><p>We can use a numerical integrator, such as MATLAB's <a href="http://www.mathworks.de/de/help/matlab/ref/integral2.html"><tt>integral2</tt></a>, to compute the area moment of inertia in the previous example. A numerical integrator might return slightly less accurate results, but other than that there is not much benefit from using symbolic integration there.</p><p>But what if we consider the cross section of a more general elliptical tube whose shape is defined by arbitrary symbolic parameters?</p><p>For example, we want to compute the area moment of inertia of this elliptical tube.</p><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/LateralCutMoreGeneral.png" alt=""> </p><p>Its contour lines are still ellipses, but they are defined by the symbolic parameters $r_1$, $r_2$, $R_1$ and $R_2$:</p><div><ul><li>$y = \pm R_2 \, \sqrt{1 - \frac{x^2}{R_1^2}}$ describe the outer contour line for $x \in [-R_1,R_1]$.</li><li>$y = \pm r_2 \, \sqrt{1 - \frac{x^2}{r_1^2}}$ describe the inner contour line for $x \in [-r_1,r_1]$.</li></ul></div><p>Now we need to compute these integrals:</p><p>$$I_1 = {\int\int}_{A_1} y^2 \, \mathrm dA_1 = \int_0^{r_1} \int_{r_2 \, \sqrt{1 -
\frac{x^2}{r_1^2}}}^{R_2 \, \sqrt{1 - \frac{x^2}{R_1^2}}} y^2 \, \mathrm dy \,
\mathrm dx,$$</p><p>$$I_2 = {\int\int}_{A_2} y^2 \, \mathrm dA_2 = \int_{r_1}^{R_1}
\int_{0}^{R_2 \, \sqrt{1 - \frac{x^2}{R_1^2}}} y^2\, \mathrm dy\, \mathrm dx.$$</p><p>Although the situation is more complicated now, we can still use the same strategy as above, using symbolic variables instead of numbers. Nevertheless, we need to add one more step: specify relationships between symbolic parameters. This is because the variables $r_1$, $r_2$, $R_1$, and $R_2$ can be any complex number, unless we explicitly restrict their values. For example, the system does not know if these variables are positive or negative, if $r_1 &lt; R_1$ or otherwise. In this example, we want to specify that $r_1&gt;0$, $r_2&gt;0$, $R_1&gt;r_1$, and $R_2&gt;r_2$. In the Symbolic Math Toolbox, such restrictions are called <i>assumptions on variables</i>. They can be set by using the <a href="http://www.mathworks.de/de/help/matlab/ref/assume.html"><tt>assume</tt></a> and <a href="http://www.mathworks.de/de/help/matlab/ref/assumeAlso.html"><tt>assumeAlso</tt></a> functions:</p><pre class="codeinput">syms <span class="string">x</span> <span class="string">y</span> <span class="string">r1</span> <span class="string">r2</span> <span class="string">R1</span> <span class="string">R2</span>;
assume(r1 &gt; 0);
assume(r2 &gt; 0);
assumeAlso(r1 &lt; R1);
assumeAlso(r2 &lt; R2);
I1 = int(int(y^2, y, r2*sqrt(1-x^2/r1^2), R2*sqrt(1-x^2/R1^2)), x, 0, r1);
I2 = int(int(y^2, y, 0, R2*sqrt(1-x^2/R1^2)), x, r1, R1);
Ixgeneral = 4 * (I1 + I2);
pretty(Ixgeneral)
</pre><pre class="codeoutput"> 
        /          4     / r1 \ \         /                     4     / r1 \ \ 
        |      3 R1  asin| -- | |         |             4   3 R1  asin| -- | | 
      3 |                \ R1 / |       3 |      3 pi R1              \ R1 / | 
  4 R2  | #1 + ---------------- |   4 R2  | #1 - -------- + ---------------- | 
        \             8         /         \         16             8         / 
  ------------------------------- - ------------------------------------------ 
                   3                                      3 
               3 R1                                   3 R1 
   
                3 
        pi r1 r2 
      - --------- 
            4 
   
  where 
   
           /     2        3 \ 
           | 5 R1  r1   r1  |    2     2 1/2 
     #1 == | -------- - --- | (R1  - r1 ) 
           \    8        4  /
</pre><p>Now, let's substitute our symbolic parameters  with the same values that we had in the first example. Do we get the same result? Let's double-check: when substituting $r_1=2,r_2,=1,R_1=3,R_2=2$ in <tt>Ixgeneral</tt>, do we get the same result for <tt>Ix</tt> as obtained for the section initially considered?</p><p>As expected, the general solution <tt>Ixgeneral</tt> reduces to the specific solution <tt>Ix</tt> when we substitute our original dimensions:</p><pre class="codeinput">vpa(subs(Ixgeneral, [r1, R1, r2, R2],[2, 3, 1, 2]), 5)
</pre><pre class="codeoutput">ans =
17.279
</pre><p>Note that it is essential to set the assumptions on $r_1$, $r_2$, $R_1$ and $R_2$. By default, the Symbolic Math Toolbox assumes that all variables including symbolic parameters are arbitrary complex numbers. This makes computing integrals much more complicated and time-consuming. For example, try computing <tt>Ixgeneral</tt> without setting the assumptions on $r_1$, $r_2$, $R_1$ and $R_2$. In general, it can be impossible to even get the result without any additional assumptions.</p><h4>How to Create MuPAD Graphics Shown in This Article<a name="2415b2ac-5410-444a-8c2b-f15693021763"></a></h4><p>To generate the graphics shown in this article, use <a href="http://www.mathworks.de/discovery/mupad.html">MuPAD Notebook app</a>. Note that the code in this section does not run in the MATLAB Command Window.</p><p>To open the MuPAD Notebook app:</p><div><ol><li>On the MATLAB Toolstrip, click the Apps tab.</li><li>On the Apps tab, click the down arrow at the end of the Apps section.</li><li>Under Math, Statistics and Optimization, click the MuPAD Notebook button.</li></ol></div><p>Alternatively, type <tt>mupad</tt> in the MATLAB Command Window.</p><p>Paste the following commands to a MuPAD notebook to obtain the four graphics used above:</p><pre>Ellipse:= (x,a,b) -&gt; sqrt(b^2*(1-x^2/a^2)):</pre><pre>f1 := plot::Function2d(Ellipse(x,2,1), x = -3..3):
f2 := plot::Function2d(Ellipse(x,3,2), x = -3..3):
f3 := plot::Function2d(Ellipse(x,3,2), x = -3..-2):
f4 := plot::Function2d(Ellipse(x,3,2), x = 2..3):</pre><pre>f5 := plot::Function2d(-Ellipse(x,2,1), x = -3..3):
f6 := plot::Function2d(-Ellipse(x,3,2), x = -3..3):
f7 := plot::Function2d(-Ellipse(x,3,2), x = -3..-2):
f8 := plot::Function2d(-Ellipse(x,3,2), x = 2..3):</pre><pre>f9 := plot::Function2d(Ellipse(x,2,1), x = 0..2, VerticalAsymptotesVisible = FALSE):
f10 := plot::Function2d(Ellipse(x,3,2), x = 0..3, VerticalAsymptotesVisible = FALSE):
f11 := plot::Function2d(Ellipse(x,3,2), x = 2..3, VerticalAsymptotesVisible = FALSE):</pre><pre>plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
     plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
     Scaling = Constrained,
     GridVisible = TRUE,
     VerticalAsymptotesVisible = FALSE,
     Height = 120, Width = 200,
     Header = "Cross section of elliptical tube (x-y-plane)"):</pre><pre>plot(plot::Hatch(f9,f10),plot::Hatch(f11),f9,f10,
     Scaling = Constrained,
     GridVisible = TRUE,
     Height = 120, Width = 200,
     Header = "Restriction to first quadrant (x-y-plane)"):</pre><pre>plot(plot::Hatch(f9,f10,Color=RGB::Magenta),plot::Hatch(f11,Color = RGB::Green),f9,f10,
     Scaling=Constrained,
     GridVisible = TRUE,
     plot::Text2d("A1",[1.0,1.25]),
     plot::Text2d("A2",[2.5,0.25]),
     Height = 120, Width = 200,
     Header = "Integration areas"):</pre><pre>plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
     plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
     plot::Text2d("r1",[1.8,0.05]),
     plot::Text2d("r2",[0.05,0.85]),
     plot::Text2d("R1",[2.74,0.05]),
     plot::Text2d("R2",[0.05,1.84]),
     Scaling = Constrained,
     GridVisible = TRUE,
     VerticalAsymptotesVisible = FALSE,
     XTicksLabelsVisible = FALSE,
     YTicksLabelsVisible = FALSE,
     ViewingBox = [-3.5..3.5,-2.5..2.5],
     Height = 120, Width = 200,
     Header = "Cross section of elliptical tube (more general situation)"):</pre><h4>Have You Tried Symbolic Math Toolbox?<a name="ebec3076-fed9-49e8-967d-2c5a6a31fea0"></a></h4><p>Have you used the Symbolic Math Toolbox in computations related to mechanics? Let me know <a href="http://blogs.mathworks.com/loren/?p=684#respond">here</a>.</p><script language="JavaScript"> <!-- 
    function grabCode_75b0bee11e3e4c56aafb679a67295a76() {
        // 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='75b0bee11e3e4c56aafb679a67295a76 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 75b0bee11e3e4c56aafb679a67295a76';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_75b0bee11e3e4c56aafb679a67295a76()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><!--
75b0bee11e3e4c56aafb679a67295a76 ##### SOURCE BEGIN #####
%% Using Symbolic Math Toolbox to Compute Area Moments of Inertia 
% Once more I am pleased to introduce guest blogger Kai Gehrs. Kai has been 
% a Software Engineer at MathWorks for the past five years working on the 
% <http://www.mathworks.com/help/toolbox/symbolic Symbolic Math Toolbox>. 
% He has a background in mathematics and computer science. He already 
% contributed to my BLOG in the past writing about  
% <http://blogs.mathworks.com/loren/2012/07/27/using-symbolic-equations-and-symbolic-functions-in-matlab Using Symbolic Equations And Symbolic Functions In MATLAB> 
% as well as on approaches for <http://blogs.mathworks.com/loren/2011/10/25/simplifying-symbolic-results Simplifying Symbolic Results>.
% 
%% In a Nutshell: What Is This Article About?
% If you are interested in using MATLAB and the Symbolic Math Toolbox
% in teaching some basics in mechanical engineering, this might be of 
% interest to you. 
% 
% Computing _area moments of inertia_ is an important task in 
% mechanics. For example, area moments of inertia play a critical role in stress, dynamic, and stability 
% analysis of structures. In this article, we use capabilities of the 
% <www.mathworks.com/products/symbolic Symbolic Math Toolbox> to compute 
% area moments for cross sections of elliptical tubes. 
%
% We start with a basic case involving only numeric parameters, and
% then make the computations more general by introducing symbolic
% parameters. 
%
% All plots used in this article have been created in the 
% <http://www.mathworks.de/discovery/mupad.html MuPAD Notebook app>. 
% You can find the source code for these plots at the end of the article. 
%
%% Basic Example: Cross Section of an Elliptical Tube   
% The following picture shows the cross section of an elliptical tube. 
%
% <<lateralCut.png>>
%
% The following ellipses define outer and inner contours of the section:
%
% * $y = \pm 2 \, \sqrt{1 - \frac{x^2}{9}}$ describe the _outer_ 
% contour line for $x \in [-3,3]$.
% * $y = \pm \sqrt{1 - \frac{x^2}{4}}$ describe the _inner_ 
% contour line for $x \in [-2,2]$. 
%
% We will compute the area moment of inertia of this section with respect 
% to the $x$-axis. 
%
%% Area Moment Of Inertia
% The moment of inertia of an area $A$ with respect to the $x$-axis 
% is defined in terms of the double integral
% 
% $$I_x = {\int \int}_A y^2\, \mathrm{d}A.$$
%
% You can find this definition on 
% <http://en.wikipedia.org/wiki/Second_moment_of_area Wikipedia>. 
%
%% Math Behind This Example
% In our example, the area $A$ is the hatched area shown in the 
% previous plot. Taking advantage of the symmetry of the section with respect 
% to both the $x$- and $y$-axes, we can restrict our computations to 
% the first quadrant of the $x-y$-plane.
%
% <<UpperQuarterLateralCut.png>>
%
% To compute the necessary double integral over the hatched area, 
% we divide this area into two separate areas $A1$ and $A2$. 
%
% <<IntegrationAreas.png>>
%
% To compute the final area moment of inertia about the x-axis, we multiply  
% the sum of the double integrals over $A_1$ and $A_2$ by four.  
%
% $$I_x = {\int\int}_A y^2 \, \mathrm dA = 4 \cdot \Big({\int\int}_{A_1}
% y^2 \, \mathrm dA_1 + {\int\int}_{A_2} y^2 \, \mathrm dA_2\Big).$$
%
% Now, we only need to compute these two double integrals. The mathematical 
% theory behind multi-dimensional integration tells us that we can rewrite 
% each of these double integrals in terms of two integrals:  
%
% $$I_1 = {\int\int}_{A_1} y^2 \, \mathrm dA_1 = \int_0^2 \int_{\sqrt{1 - 
% \frac{x^2}{4}}}^{2 \, \sqrt{1 - \frac{x^2}{9}}} y^2 \, \mathrm dy \, 
% \mathrm dx,$$ 
% 
% $$I_2 = {\int\int}_{A_2} y^2 \, \mathrm dA_2 = \int_2^3 \int_{0}^{2 \, \sqrt{1 - \frac{x^2}{9}}} 
% y^2\, \mathrm dy\, \mathrm dx.$$
% 
% The <http://www.mathworks.com/help/toolbox/symbolic/int.html |int|> 
% function from the Symbolic Math Toolbox can compute these integrals. 
%% Symbolic Integration 
%
% We define $x$ and $y$ as symbolic variables: 
syms x y;
%%
% We start computing the inner integral $\int_{\sqrt{1 - \frac{x^2}{4}}}^{2 \, \sqrt{1 -
% \frac{x^2}{9}}} y^2 \, \mathrm dy$ of $I_1$:   
innerI1 = int(y^2, y, sqrt(1-x^2/4), 2*sqrt(1-x^2/9))
%%
% Next, we integrate |innerI1| with respect to $x$ from $0$ to $2$. 
% This provides $I_1$:   
I1 = int(innerI1, x, 0, 2)
%%
% We use the same strategy to compute $I_2$. First, we compute the inner 
% integral $\int_{0}^{2 \, \sqrt{1 - \frac{x^2}{9}}} y^2\, \mathrm dy$.  
% Then, we integrate the resulting expression with respect to $x$ from $2$ 
% to $3$:
I2 = int(int(y^2, y, 0, 2*sqrt(1-x^2/9)), x, 2, 3);
%%
% Hence, the area moment of inertia of the elliptical tube with respect to 
% the $x$-axis is 
Ix = 4 * (I1 + I2)
%%
% We can approximate the result numerically by using the 
% <http://www.mathworks.com/help/toolbox/symbolic/vpa.html |vpa|>
% function. For example, we approximate the result using 5 significant 
% (nonzero) digits: 
vpa(Ix, 5)
%% Advanced Example: Cross Section of an Elliptical Tube Defined by Symbolic Parameters
%
% We can use a numerical integrator, such as MATLAB's 
% <http://www.mathworks.de/de/help/matlab/ref/integral2.html |integral2|>,
% to compute the area moment of inertia in the previous example. A
% numerical integrator might return slightly less accurate results, but
% other than that there is not much benefit from using symbolic
% integration there. 
%
% But what if we consider the cross section of a more general elliptical 
% tube whose shape is defined by arbitrary symbolic parameters?
%
% For example, we want to compute the area moment of inertia of this 
% elliptical tube.
% 
% <<LateralCutMoreGeneral.png>>
%
% Its contour lines are still ellipses, but they are defined by the 
% symbolic parameters $r_1$, $r_2$, $R_1$ and $R_2$: 
%
% * $y = \pm R_2 \, \sqrt{1 - \frac{x^2}{R_1^2}}$ describe the outer 
% contour line for $x \in [-R_1,R_1]$.
% * $y = \pm r_2 \, \sqrt{1 - \frac{x^2}{r_1^2}}$ describe the inner 
% contour line for $x \in [-r_1,r_1]$.
%
% Now we need to compute these integrals: 
%
% $$I_1 = {\int\int}_{A_1} y^2 \, \mathrm dA_1 = \int_0^{r_1} \int_{r_2 \, \sqrt{1 - 
% \frac{x^2}{r_1^2}}}^{R_2 \, \sqrt{1 - \frac{x^2}{R_1^2}}} y^2 \, \mathrm dy \, 
% \mathrm dx,$$ 
% 
% $$I_2 = {\int\int}_{A_2} y^2 \, \mathrm dA_2 = \int_{r_1}^{R_1} 
% \int_{0}^{R_2 \, \sqrt{1 - \frac{x^2}{R_1^2}}} y^2\, \mathrm dy\, \mathrm dx.$$ 
%
% Although the situation is more complicated now, we can still use the same
% strategy as above, using symbolic variables instead of numbers.
% Nevertheless, we need to add one more step: specify relationships between 
% symbolic parameters. This is because the variables $r_1$, $r_2$, $R_1$, 
% and $R_2$ can be any complex number, unless we explicitly restrict their 
% values. For example, the system does not know if these variables are 
% positive or negative, if $r_1 < R_1$ or otherwise. In this example, we 
% want to specify that $r_1>0$, $r_2>0$, $R_1>r_1$, and $R_2>r_2$. In the 
% Symbolic Math Toolbox, such restrictions are called _assumptions on 
% variables_. They can be set by using the 
% <http://www.mathworks.de/de/help/matlab/ref/assume.html |assume|>  
% and 
% <http://www.mathworks.de/de/help/matlab/ref/assumeAlso.html |assumeAlso|>  
% functions: 
syms x y r1 r2 R1 R2;
assume(r1 > 0);
assume(r2 > 0);
assumeAlso(r1 < R1); 
assumeAlso(r2 < R2);
I1 = int(int(y^2, y, r2*sqrt(1-x^2/r1^2), R2*sqrt(1-x^2/R1^2)), x, 0, r1);
I2 = int(int(y^2, y, 0, R2*sqrt(1-x^2/R1^2)), x, r1, R1);
Ixgeneral = 4 * (I1 + I2);
pretty(Ixgeneral)
%%
% Now, let's substitute our symbolic parameters  with the same values that
% we had in the first example. Do we get the same result? Let's double-check: 
% when substituting $r_1=2,r_2,=1,R_1=3,R_2=2$ in |Ixgeneral|, do we get the 
% same result for |Ix| as obtained for the section initially considered?
%
% As expected, the general solution |Ixgeneral| reduces to the specific 
% solution |Ix| when we substitute our original dimensions:
vpa(subs(Ixgeneral, [r1, R1, r2, R2],[2, 3, 1, 2]), 5)
%%
% Note that it is essential to set the assumptions on $r_1$, $r_2$, $R_1$ 
% and $R_2$. By default, the Symbolic Math Toolbox assumes that all variables 
% including symbolic parameters are arbitrary complex numbers. This makes 
% computing integrals much more complicated and time-consuming. For example, 
% try computing |Ixgeneral| without setting the assumptions on $r_1$, $r_2$, 
% $R_1$ and $R_2$. In general, it can be impossible to even get the
% result without any additional assumptions.
%
%% How to Create MuPAD Graphics Shown in This Article
% To generate the graphics shown in this article, use 
% <http://www.mathworks.de/discovery/mupad.html MuPAD Notebook app>. 
% Note that the code in this section does not run in the MATLAB Command 
% Window.  
% 
% To open the MuPAD Notebook app: 
% 
% # On the MATLAB Toolstrip, click the Apps tab. 
% # On the Apps tab, click the down arrow at the end of the Apps section.
% # Under Math, Statistics and Optimization, click the MuPAD Notebook button.
% 
% Alternatively, type |mupad| in the MATLAB Command Window. 
%
% Paste the following commands to a MuPAD notebook to obtain the four 
% graphics used above:
%
%  Ellipse:= (x,a,b) -> sqrt(b^2*(1-x^2/a^2)):
%  
%  f1 := plot::Function2d(Ellipse(x,2,1), x = -3..3):
%  f2 := plot::Function2d(Ellipse(x,3,2), x = -3..3):
%  f3 := plot::Function2d(Ellipse(x,3,2), x = -3..-2):
%  f4 := plot::Function2d(Ellipse(x,3,2), x = 2..3):
%  
%  f5 := plot::Function2d(-Ellipse(x,2,1), x = -3..3):
%  f6 := plot::Function2d(-Ellipse(x,3,2), x = -3..3):
%  f7 := plot::Function2d(-Ellipse(x,3,2), x = -3..-2):
%  f8 := plot::Function2d(-Ellipse(x,3,2), x = 2..3):
%  
%  f9 := plot::Function2d(Ellipse(x,2,1), x = 0..2, VerticalAsymptotesVisible = FALSE):
%  f10 := plot::Function2d(Ellipse(x,3,2), x = 0..3, VerticalAsymptotesVisible = FALSE):
%  f11 := plot::Function2d(Ellipse(x,3,2), x = 2..3, VerticalAsymptotesVisible = FALSE):
%  
%  plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
%       plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
%       Scaling = Constrained, 
%       GridVisible = TRUE, 
%       VerticalAsymptotesVisible = FALSE,
%       Height = 120, Width = 200,
%       Header = "Cross section of elliptical tube (x-y-plane)"):
%  
%  plot(plot::Hatch(f9,f10),plot::Hatch(f11),f9,f10,
%       Scaling = Constrained,
%       GridVisible = TRUE,
%       Height = 120, Width = 200,
%       Header = "Restriction to first quadrant (x-y-plane)"):
%  
%  plot(plot::Hatch(f9,f10,Color=RGB::Magenta),plot::Hatch(f11,Color = RGB::Green),f9,f10,
%       Scaling=Constrained,
%       GridVisible = TRUE, 
%       plot::Text2d("A1",[1.0,1.25]),
%       plot::Text2d("A2",[2.5,0.25]),
%       Height = 120, Width = 200,
%       Header = "Integration areas"):
%  
%  plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
%       plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
%       plot::Text2d("r1",[1.8,0.05]),
%       plot::Text2d("r2",[0.05,0.85]),
%       plot::Text2d("R1",[2.74,0.05]),
%       plot::Text2d("R2",[0.05,1.84]),
%       Scaling = Constrained, 
%       GridVisible = TRUE, 
%       VerticalAsymptotesVisible = FALSE,
%       XTicksLabelsVisible = FALSE,
%       YTicksLabelsVisible = FALSE,
%       ViewingBox = [-3.5..3.5,-2.5..2.5],
%       Height = 120, Width = 200,
%       Header = "Cross section of elliptical tube (more general situation)"):
%% Have You Tried Symbolic Math Toolbox?
% Have you used the Symbolic Math Toolbox in computations related to 
% mechanics? Let me know <http://blogs.mathworks.com/loren/?p=684#respond here>.
##### SOURCE END ##### 75b0bee11e3e4c56aafb679a67295a76
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/GAkkzQGU4nE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/04/26/using-symbolic-math-toolbox-to-compute-area-moments-of-inertia/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/04/26/using-symbolic-math-toolbox-to-compute-area-moments-of-inertia/</feedburner:origLink></item>
		<item>
		<title>MATLAB to FPGA using HDL Coder(TM)</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/kOoWp0H4zmg/</link>
		<comments>http://blogs.mathworks.com/loren/2013/04/11/matlab-to-fpga-using-hdl-codertm/#comments</comments>
		<pubDate>Thu, 11 Apr 2013 12:22:41 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=673</guid>
		<description><![CDATA[It's my pleasure to introduce guest blogger Kiran Kintali. Kiran is the product development lead for HDL Coder at MathWorks. In this post, Kiran introduces a new capability in HDL Coder&#8482; that generates synthesizable VHDL/Verilog code directly from MATLAB and highlights some of the key features of this new MATLAB based workflow.ContentsIntroduction to HDL Code [...]]]></description>
				<content:encoded><![CDATA[
<div class="content"><!--introduction--><p>It's my pleasure to introduce guest blogger Kiran Kintali. Kiran is the product development lead for <a href="http://www.mathworks.com/products/hdl-coder">HDL Coder</a> at MathWorks. In this post, Kiran introduces a new capability in HDL Coder&#8482; that generates synthesizable VHDL/Verilog code directly from MATLAB and highlights some of the key features of this new MATLAB based workflow.</p><!--/introduction--><h3>Contents</h3><div><ul><li><a href="#70424a2f-088b-4758-8de0-5fac5103cdcd">Introduction to HDL Code Generation from MATLAB</a></li><li><a href="#91a6f507-30f4-41eb-9876-b2d47f392316">MATLAB to Hardware Workflow</a></li><li><a href="#ae2259c5-71e6-4582-ae3c-dd8824b7a4f5">Example MATLAB Algorithm</a></li><li><a href="#e5de1a1f-d9cb-4b08-9982-2f47f2c5d4e2">Example MATLAB Test Bench</a></li><li><a href="#eb8b6ef6-825c-43f1-8ea0-8d9f9ed13006">HDL Workflow Advisor</a></li><li><a href="#d1cf933b-d17d-4d81-8d56-2a0f984df493">Design Space Exploration and Optimization Options</a></li><li><a href="#08ade249-3944-44d2-95db-db0d7060c5de">Best Practices</a></li><li><a href="#cdf41669-3ba0-44ac-8908-22d323960590">Conclusion</a></li></ul></div><h4>Introduction to HDL Code Generation from MATLAB<a name="70424a2f-088b-4758-8de0-5fac5103cdcd"></a></h4><p>If you are using MATLAB to model digital signal processing (DSP) or video and image processing algorithms that eventually end up in FPGAs or ASICs, read on...</p><p>FPGAs provide a good compromise between general purpose processors (GPPs) and application specific integrated circuits (ASICs). GPPs are fully programmable but are less efficient in terms of power and performance; ASICs implement dedicated functionality and show the best power and performance characteristics, but require extremely expensive design validation and implementation cycles. FPGAs are also used for prototyping in ASIC workflows for hardware verification and early software development.</p><p>Due to the order of magnitude performance improvement when running high-throughput, high-performance applications, algorithm designers are increasingly using FPGAs to prototype and validate their innovations instead of using traditional processors. However, many of the algorithms are implemented in MATLAB due to the simple-to-use programming model and rich analysis and visualization capabilities. When targeting FPGAs or ASICs these MATLAB algorithms have to be manually translated to HDL.</p><p>For many algorithm developers who are well-versed with software programming paradigms, mastering the FPGA design workflow is a challenge. Unlike software algorithm development, hardware development requires them to <b><i>think parallel</i></b>. Other obstacles include: learning the VHDL or Verilog language, mastering IDEs from FPGA vendors, and understanding esoteric terms like "multi-cycle path" and "delay balancing".</p><p>In this post, I describe an easier path from MATLAB to FPGAs. I will show how you can automatically generate HDL code from your MATLAB algorithm, implement the HDL code on an FPGA, and use MATLAB to verify your HDL code.</p><h4>MATLAB to Hardware Workflow<a name="91a6f507-30f4-41eb-9876-b2d47f392316"></a></h4><p>The process of translating MATLAB designs to hardware consists of the following steps:</p><div><ol><li>Model your algorithm in MATLAB - use MATLAB to simulate, debug, and iteratively test and optimize the design.</li><li>Generate HDL code - automatically create HDL code for FPGA prototyping.</li><li>Verify HDL code - reuse your MATLAB test bench to verify the generated HDL code.</li><li>Create and verify FPGA prototype - implement and verify your design on FPGAs.</li></ol></div><p>There are some unique challenges in translating MATLAB to hardware. MATLAB code is procedural and can be highly abstract; it can use floating-point data and has no notion of time. Complex loops can be inferred from matrix operations and toolbox functions.</p><p>Implementing MATLAB code in hardware involves:</p><div><ul><li>Converting floating-point MATLAB code to fixed-point MATLAB code with optimized bit widths suitable for efficient hardware generation.</li><li>Identifying and mapping procedural constructs to concurrent area- and speed-optimized hardware operations.</li><li>Introducing the concept of time by adding clocks and clock rates to schedule the operations in hardware.</li><li>Creating resource-shared architectures to implement expensive operators like multipliers and for-loop bodies.</li><li>Mapping large persistent arrays to block RAM in hardware</li></ul></div><p>HDL Coder&#8482; simplifies the above tasks though workflow automation.</p><h4>Example MATLAB Algorithm<a name="ae2259c5-71e6-4582-ae3c-dd8824b7a4f5"></a></h4><p>Let&#8217;s take a MATLAB function implementing histogram equalization and go through this workflow. This algorithm, implemented in MATLAB, enhances image contrast by transforming the values in an intensity image so that the histogram of the output image is approximately flat.</p><p><i>type mlhdlc_heq.m</i></p><pre class="language-matlab"><span class="comment">% Histogram Equalization Algorithm</span>
<span class="keyword">function</span> [pixel_out] = mlhdlc_heq(x_in, y_in, pixel_in, width, height)
</pre><pre class="language-matlab"><span class="keyword">persistent</span> histogram
<span class="keyword">persistent</span> transferFunc
<span class="keyword">persistent</span> histInd
<span class="keyword">persistent</span> cumSum
</pre><pre class="language-matlab"><span class="keyword">if</span> isempty(histogram)
    histogram = zeros(1, 2^8);
    transferFunc = zeros(1, 2^8);
    histInd = 0;
    cumSum = 0;
<span class="keyword">end</span>
</pre><pre class="language-matlab"><span class="comment">% Figure out indices based on where we are in the frame</span>
<span class="keyword">if</span> y_in &lt; height &amp;&amp; x_in &lt; width <span class="comment">% valid pixel data</span>
    histInd = pixel_in + 1;
<span class="keyword">elseif</span> y_in == height &amp;&amp; x_in == 0 <span class="comment">% first column of height+1</span>
    histInd = 1;
<span class="keyword">elseif</span> y_in &gt;= height <span class="comment">% vertical blanking period</span>
    histInd = min(histInd + 1, 2^8);
<span class="keyword">elseif</span> y_in &lt; height <span class="comment">% horizontal blanking - do nothing</span>
    histInd = 1;
<span class="keyword">end</span>
</pre><pre class="language-matlab"><span class="comment">%Read histogram</span>
histValRead = histogram(histInd);
</pre><pre class="language-matlab"><span class="comment">%Read transfer function</span>
transValRead = transferFunc(histInd);
</pre><pre class="language-matlab"><span class="comment">%If valid part of frame add one to pixel bin and keep transfer func val</span>
<span class="keyword">if</span> y_in &lt; height &amp;&amp; x_in &lt; width
    histValWrite = histValRead + 1; <span class="comment">%Add pixel to bin</span>
    transValWrite = transValRead; <span class="comment">%Write back same value</span>
    cumSum = 0;
<span class="keyword">elseif</span> y_in &gt;= height <span class="comment">%In blanking time index through all bins and reset to zero</span>
    histValWrite = 0;
    transValWrite = cumSum + histValRead;
    cumSum = transValWrite;
<span class="keyword">else</span>
    histValWrite = histValRead;
    transValWrite = transValRead;
<span class="keyword">end</span>
</pre><pre class="language-matlab"><span class="comment">%Write histogram</span>
histogram(histInd) = histValWrite;
</pre><pre class="language-matlab"><span class="comment">%Write transfer function</span>
transferFunc(histInd) = transValWrite;
</pre><pre class="language-matlab">pixel_out = transValRead;
</pre><h4>Example MATLAB Test Bench<a name="e5de1a1f-d9cb-4b08-9982-2f47f2c5d4e2"></a></h4><p>Here is the test bench that verifies that the algorithm works with an example image. (Note that this testbench uses Image Processing Toolbox functions for reading the original image and plotting the transformed image after equalization.)</p><p><i>type mlhdlc_heq_tb.m</i></p><pre class="language-matlab"><span class="comment">%% Test bench for Histogram Equalization Algorithm</span>
clear <span class="string">mlhdlc_heq</span>;
testFile = <span class="string">'office.png'</span>;
RGB = imread(testFile);
</pre><pre class="language-matlab"><span class="comment">% Get intensity part of color image</span>
YCBCR = rgb2ycbcr(RGB);
imgOrig = YCBCR(:,:,1);
</pre><pre class="language-matlab">[height, width] = size(imgOrig);
imgOut = zeros(height,width);
hBlank = 20;
<span class="comment">% make sure we have enough vertical blanking to filter the histogram</span>
vBlank = ceil(2^14/(width+hBlank));
</pre><pre class="language-matlab"><span class="keyword">for</span> frame = 1:2
    disp([<span class="string">'working on frame: '</span>, num2str(frame)]);
    <span class="keyword">for</span> y_in = 0:height+vBlank-1
        <span class="comment">%disp(['frame: ', num2str(frame), ' of 2, row: ', num2str(y_in)]);</span>
        <span class="keyword">for</span> x_in = 0:width+hBlank-1
            <span class="keyword">if</span> x_in &lt; width &amp;&amp; y_in &lt; height
                pixel_in = double(imgOrig(y_in+1, x_in+1));
            <span class="keyword">else</span>
                pixel_in = 0;
            <span class="keyword">end</span>
</pre><pre>             [pixel_out] = mlhdlc_heq(x_in, y_in, pixel_in, width, height);</pre><pre>             if x_in &lt; width &amp;&amp; y_in &lt; height
                 imgOut(y_in+1,x_in+1) = pixel_out;
             end
         end
     end
 end</pre><pre class="language-matlab"><span class="comment">% Make color image from equalized intensity image</span>
<span class="comment">% Rescale image</span>
imgOut = double(imgOut);
imgOut(:) = imgOut/max(imgOut(:));
imgOut = uint8(imgOut*255);
</pre><pre class="language-matlab">YCBCR(:,:,1) = imgOut;
RGBOut = ycbcr2rgb(YCBCR);
</pre><pre class="language-matlab">figure(1)
subplot(2,2,1); imshow(RGB, []);
title(<span class="string">'Original Image'</span>);
subplot(2,2,2); imshow(RGBOut, []);
title(<span class="string">'Equalized Image'</span>);
subplot(2,2,3); hist(double(imgOrig(:)),2^14-1);
title(<span class="string">'Histogram of original Image'</span>);
subplot(2,2,4); hist(double(imgOut(:)),2^14-1);
title(<span class="string">'Histogram of equalized Image'</span>);
</pre><p>Let's simulate this algorithm to see the results.</p><pre class="codeinput">mlhdlc_heq_tb
</pre><pre class="codeoutput">working on frame: 1
working on frame: 2
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/ml2hdlBlog_01.png" alt=""> <h4>HDL Workflow Advisor<a name="eb8b6ef6-825c-43f1-8ea0-8d9f9ed13006"></a></h4><p>The HDL Workflow Advisor (see the snapshot below) helps automate the steps and provides a guided path from MATLAB to hardware. You can see the following key steps of the workflow in the left pane of the workflow advisor:</p><div><ol><li>Fixed-Point Conversion</li><li>HDL Code Generation</li><li>HDL Verification</li><li>HDL Synthesis and Analysis</li></ol></div><p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/hdlwfa.png" alt=""> </p><p>Let's look at each workflow step in detail.</p><p><b>Fixed-Point Conversion</b></p><p>Signal processing applications are typically implemented using floating-point operations in MATLAB. However, for power, cost, and performance reasons, these algorithms need to be converted to use fixed-point operations when targeting hardware. Fixed-point conversion can be very challenging and time-consuming, typically demanding 25 to 50 percent of the total design and implementation time.  The automatic floating-point to fixed-point conversion workflow in HDL Coder&#8482; can greatly simplify and accelerate this conversion process.</p><p>The floating-point to fixed-point conversion workflow consists of the following steps:</p><div><ol><li>Verify that the floating-point design is compatible with code generation.</li><li>Propose fixed-point types based on computed ranges, either through the simulation of the testbench or through static analysis that propagates design ranges to compute derived ranges for all the variables.</li><li>Generate fixed-point MATLAB code by applying proposed fixed-point types.</li><li>Verify the generated fixed-point code and compare the numerical accuracy of the generated fixed-point code with the original floating point code.</li></ol></div><p>Note that this step is optional. You can skip this step if your MATLAB design is already implemented in fixed-point.</p><p><b>HDL Code Generation</b></p><p>The HDL Code Generation step generates HDL code from the fixed-point MATLAB code. You can generate either VHDL or Verilog code that implements your MATLAB design. In addition to generating synthesizable HDL code, HDL Coder&#8482; also generates various reports, including a traceability report that helps you navigate between your MATLAB code and the generated HDL code, and a resource utilization report that shows you, at the algorithm level, approximately what hardware resources are needed to implement the design, in terms of adders, multipliers, and RAMs.</p><p>During code generation, you can specify various optimization options to explore the design space without having to modify your algorithm. In the Design Space Exploration and Optimization Options section below, you can see how you can modify code generation options and optimize your design for speed or area.</p><p><b>HDL Verification</b></p><p>Standalone HDL test bench generation:</p><p>HDL Coder&#8482; generates VHDL and Verilog test benches from your MATLAB scripts for rapid verification of generated HDL code. You can customize an HDL test bench using a variety of options that apply stimuli to the HDL code. You can also generate script files to automate the process of compiling and simulating your code in HDL simulators. These steps help to ensure the results of MATLAB simulation match the results of HDL simulation.</p><p>HDL Coder&#8482; also works with <a href="http://www.mathworks.com/products/hdl-verifier">HDL Verifier</a> to automatically generate two types of cosimulation testbenches:</p><div><ul><li>HDL cosimulation-based verification works with Mentor Graphics&reg; ModelSim&reg; and QuestaSim&reg;, where MATLAB and HDL simulation happen in lockstep.</li><li>FPGA-in-the-Loop simulation allows you to run a MATLAB simulation with an FPGA board in strict synchronization. You can use MATLAB to feed real world data into your design on the FPGA, and ensure that the algorithm will behave as expected when implemented in hardware.</li></ul></div><p><b>HDL Synthesis</b></p><p>Apart from the language-related challenges, programming for FPGAs requires the use of complex EDA tools. Generating a bitstream from the HDL design and programming the FPGA can be daunting tasks. HDL Coder&#8482; provides automation here, by creating project files for Xilinx&reg; and Altera&reg; that are configured with the generated HDL code. You can use the workflow steps to synthesize the HDL code within the MATLAB environment, see the results of synthesis, and iterate on the MATLAB design to improve synthesis results.</p><h4>Design Space Exploration and Optimization Options<a name="d1cf933b-d17d-4d81-8d56-2a0f984df493"></a></h4><p>HDL Coder&#8482; provides the following optimizations to help you explore the design space trade-offs between area and speed. You can use these options to explore various architectures and trade-offs without having to manually rewrite your algorithm.</p><p><b>Speed Optimizations</b></p><div><ul><li><b>Pipelining</b> : To improve the design&#8217;s clock frequency, HDL Coder enables you to insert pipeline registers in various locations within your design. For example, you can insert registers at the design inputs and outputs, and also at the output of a given MATLAB variable in your algorithm.</li><li><b>Distributed Pipelining</b> : HDL Coder also provides an optimization based on retiming to automatically move pipeline registers you have inserted to maximize clock frequency, by minimizing the delay through combinational paths in your design.</li></ul></div><p><b>Area Optimizations</b></p><div><ul><li><b>RAM mapping</b>: HDL Coder&#8482; maps matrices to wires or registers in hardware. If persistent matrix variables are mapped to registers, they can take up a large amount of FPGA area. HDL Coder&#8482; automatically maps persistent matrices to block RAM to improve area efficiency. The challenge in mapping MATLAB matrices to block RAM is that block RAM in hardware typically has a limited set of read and write ports. HDL Coder&#8482; solves this problem by automatically partitioning and scheduling the matrix reads and writes to honor the block RAM&#8217;s port constraints, while still honoring the other control- and data-dependencies in the design.</li><li><b>Resource sharing</b>: This optimization identifies functionally equivalent multiplier operations in MATLAB code and shares them. You can control the amount of multiplier sharing in the design.</li><li><b>Loop streaming</b>: A MATLAB for-loop creates a FOR_GENERATE loop in VHDL. The body of the loop is replicated as many times in hardware as the number of loop iterations. This results in an inefficient use of area. The loop streaming optimization creates a single hardware instance of the loop body that is time-multiplexed across loop iterations.</li><li><b>Constant multiplier optimization</b>: This design level optimization converts constant multipliers into shift and add operations using canonical signed digit (CSD) techniques.</li></ul></div><h4>Best Practices<a name="08ade249-3944-44d2-95db-db0d7060c5de"></a></h4><p>Now, let's look at few best practices related to writing MATLAB code when targeting FPGAs.</p><p><b>When writing a MATLAB design:</b></p><div><ul><li>Use the code generation subset of MATLAB supported for HDL code generation.</li><li>Keep the top-level interface as simple as possible. The top-level function size, types, and complexity determine the interface of the chip implemented in hardware.</li><li>Do not pass in a big chunk of parallel data into the design. Parallel data requires a large number of IO pins on the chip, and would probably not be synthesizable.  In a typical image processing design, you should serialize the pixels as inputs and buffer them internally in the algorithm.</li></ul></div><p><b>When writing a MATLAB test bench:</b></p><div><ul><li>Call the design from the testbench function.</li><li>Exercise the design thoroughly. This is particularly important for floating-point to fixed-point conversion, where HDL Coder&#8482; determines the ranges of the variables in the algorithm based on the values the testbench assigns to the variables. You can reuse this testbench to generate an HDL testbench for testing the generated hardware.</li><li>Simulate the design with the testbench prior to code generation to make sure there are no simulation errors, and to make sure all the required files are on the path.</li></ul></div><h4>Conclusion<a name="cdf41669-3ba0-44ac-8908-22d323960590"></a></h4><p>HDL Coder&#8482; provides a seamless workflow when you want to implement your algorithm in an FPGA. In this post, I have shown you how to take an image processing algorithm written in MATLAB, convert it to fixed-point, generate HDL code, verify the generated HDL code using the test bench, and finally, synthesize the design and implement it in hardware.</p><p>See this <a href="http://www.mathworks.com/company/newsroom/FLIR-Speeds-Thermal-Imaging-FPGA-Development-Through-Automatic-HDL-Generation-From-MATLAB.html">article</a> about how one of the HDL Coder customers, FLIR has used MATLAB to HDL workflow to achieve good results. You can also learn more about this workflow using the product examples <a href="http://www.mathworks.com/products/hdl-coder/examples.html">located here.</a></p><p>We hope this brief introduction to the HDL Coder&#8482; and MATLAB-to-HDL code generation, verification framework has shown how you can quickly get started on implementing your MATLAB designs and target FPGAs. Please let us know in the comments for this post how you might use this new functionality. Or, if you've already tried using HDL Coder&#8482;, let us know about your experiences <a href="http://blogs.mathworks.com/loren/?p=673#respond">here</a>.</p><script language="JavaScript"> <!-- 
    function grabCode_62189eb44b6e46ffafdbf080e751390b() {
        // 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='62189eb44b6e46ffafdbf080e751390b ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 62189eb44b6e46ffafdbf080e751390b';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_62189eb44b6e46ffafdbf080e751390b()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><!--
62189eb44b6e46ffafdbf080e751390b ##### SOURCE BEGIN #####
%% MATLAB to FPGA using HDL Coder(TM)
% It's my pleasure to introduce guest blogger Kiran Kintali. Kiran is the
% product development lead for <http://www.mathworks.com/products/hdl-coder
% HDL Coder> at MathWorks. In this post, Kiran introduces a new capability
% in HDL Coder(TM) that generates synthesizable VHDL/Verilog code directly
% from MATLAB and highlights some of the key features of this new MATLAB
% based workflow.

%% Introduction to HDL Code Generation from MATLAB
% If you are using MATLAB to model digital signal processing (DSP) or video
% and image processing algorithms that eventually end up in FPGAs or ASICs,
% read on...
%% 
% FPGAs provide a good compromise between general purpose processors (GPPs)
% and application specific integrated circuits (ASICs). GPPs are fully
% programmable but are less efficient in terms of power and performance;
% ASICs implement dedicated functionality and show the best power and
% performance characteristics, but require extremely expensive design
% validation and implementation cycles. FPGAs are also used for prototyping
% in ASIC workflows for hardware verification and early software
% development.
%%
% Due to the order of magnitude performance improvement when running
% high-throughput, high-performance applications, algorithm designers are
% increasingly using FPGAs to prototype and validate their innovations
% instead of using traditional processors. However, many of the algorithms
% are implemented in MATLAB due to the simple-to-use programming model and
% rich analysis and visualization capabilities. When targeting FPGAs or
% ASICs these MATLAB algorithms have to be manually translated to HDL.
%
%% 
% For many algorithm developers who are well-versed with software
% programming paradigms, mastering the FPGA design workflow is a challenge.
% Unlike software algorithm development, hardware development requires them
% to *_think parallel_*. Other obstacles include: learning the VHDL or
% Verilog language, mastering IDEs from FPGA vendors, and understanding
% esoteric terms like "multi-cycle path" and "delay balancing".
%%
% In this post, I describe an easier path from MATLAB to FPGAs. I will show
% how you can automatically generate HDL code from your MATLAB algorithm,
% implement the HDL code on an FPGA, and use MATLAB to verify your HDL
% code.

%% MATLAB to Hardware Workflow
% The process of translating MATLAB designs to hardware consists of the
% following steps:
%
% # Model your algorithm in MATLAB - use MATLAB to simulate, debug, and
% iteratively test and optimize the design.
% # Generate HDL code - automatically create HDL code for FPGA prototyping.
% # Verify HDL code - reuse your MATLAB test bench to verify the generated
% HDL code.
% # Create and verify FPGA prototype - implement and verify your design on
% FPGAs.
%
% There are some unique challenges in translating MATLAB to hardware.
% MATLAB code is procedural and can be highly abstract; it can use
% floating-point data and has no notion of time. Complex loops can be
% inferred from matrix operations and toolbox functions.
%
% Implementing MATLAB code in hardware involves:
%
% * Converting floating-point MATLAB code to fixed-point MATLAB code with
% optimized bit widths suitable for efficient hardware generation.
% * Identifying and mapping procedural constructs to concurrent area- and
% speed-optimized hardware operations.
% * Introducing the concept of time by adding clocks and clock rates to
% schedule the operations in hardware.
% * Creating resource-shared architectures to implement expensive operators
% like multipliers and for-loop bodies.
% * Mapping large persistent arrays to block RAM in hardware
%
% HDL Coder(TM) simplifies the above tasks though workflow automation.

%% Example MATLAB Algorithm
% Letâ€™s take a MATLAB function implementing histogram equalization and go
% through this workflow. This algorithm, implemented in MATLAB, enhances
% image contrast by transforming the values in an intensity image so that
% the histogram of the output image is approximately flat.
%%
% 
% _type mlhdlc_heq.m_ 
%% 
%   % Histogram Equalization Algorithm
%   function [pixel_out] = mlhdlc_heq(x_in, y_in, pixel_in, width, height)
%   
%   persistent histogram
%   persistent transferFunc
%   persistent histInd
%   persistent cumSum
%   
%   if isempty(histogram)
%       histogram = zeros(1, 2^8);
%       transferFunc = zeros(1, 2^8);
%       histInd = 0;
%       cumSum = 0;
%   end
%   
%   % Figure out indices based on where we are in the frame
%   if y_in < height &#038;& x_in < width % valid pixel data
%       histInd = pixel_in + 1;
%   elseif y_in == height &#038;& x_in == 0 % first column of height+1
%       histInd = 1;
%   elseif y_in >= height % vertical blanking period
%       histInd = min(histInd + 1, 2^8);
%   elseif y_in < height % horizontal blanking - do nothing
%       histInd = 1;
%   end
%   
%   %Read histogram
%   histValRead = histogram(histInd);
%   
%   %Read transfer function
%   transValRead = transferFunc(histInd);
%   
%   %If valid part of frame add one to pixel bin and keep transfer func val
%   if y_in < height &#038;& x_in < width
%       histValWrite = histValRead + 1; %Add pixel to bin
%       transValWrite = transValRead; %Write back same value
%       cumSum = 0;
%   elseif y_in >= height %In blanking time index through all bins and reset to zero
%       histValWrite = 0;
%       transValWrite = cumSum + histValRead;
%       cumSum = transValWrite;
%   else
%       histValWrite = histValRead;
%       transValWrite = transValRead;
%   end
%   
%   %Write histogram
%   histogram(histInd) = histValWrite;
%   
%   %Write transfer function
%   transferFunc(histInd) = transValWrite;
%   
%   pixel_out = transValRead;
%   

%% Example MATLAB Test Bench
% Here is the test bench that verifies that the algorithm works with an
% example image. (Note that this testbench uses Image Processing Toolbox
% functions for reading the original image and plotting the transformed
% image after equalization.)
%%
% 
% _type mlhdlc_heq_tb.m_ 
%%
%   %% Test bench for Histogram Equalization Algorithm
%   clear mlhdlc_heq;
%   testFile = 'office.png';
%   RGB = imread(testFile);
%   
%   % Get intensity part of color image
%   YCBCR = rgb2ycbcr(RGB);
%   imgOrig = YCBCR(:,:,1);
%   
%   [height, width] = size(imgOrig);
%   imgOut = zeros(height,width);
%   hBlank = 20;
%   % make sure we have enough vertical blanking to filter the histogram
%   vBlank = ceil(2^14/(width+hBlank));
%   
%   for frame = 1:2
%       disp(['working on frame: ', num2str(frame)]);
%       for y_in = 0:height+vBlank-1
%           %disp(['frame: ', num2str(frame), ' of 2, row: ', num2str(y_in)]);
%           for x_in = 0:width+hBlank-1
%               if x_in < width &#038;& y_in < height
%                   pixel_in = double(imgOrig(y_in+1, x_in+1));
%               else
%                   pixel_in = 0;
%               end
%               
%               [pixel_out] = mlhdlc_heq(x_in, y_in, pixel_in, width, height);
%                          
%               if x_in < width &#038;& y_in < height
%                   imgOut(y_in+1,x_in+1) = pixel_out;
%               end
%           end
%       end
%   end
%   
%   % Make color image from equalized intensity image   
%   % Rescale image
%   imgOut = double(imgOut);
%   imgOut(:) = imgOut/max(imgOut(:));
%   imgOut = uint8(imgOut*255);
%   
%   YCBCR(:,:,1) = imgOut;
%   RGBOut = ycbcr2rgb(YCBCR);
%   
%   figure(1)
%   subplot(2,2,1); imshow(RGB, []);
%   title('Original Image');
%   subplot(2,2,2); imshow(RGBOut, []);
%   title('Equalized Image');
%   subplot(2,2,3); hist(double(imgOrig(:)),2^14-1);
%   title('Histogram of original Image');
%   subplot(2,2,4); hist(double(imgOut(:)),2^14-1);
%   title('Histogram of equalized Image');

%%
% Let's simulate this algorithm to see the results.
mlhdlc_heq_tb

%% HDL Workflow Advisor
% The HDL Workflow Advisor (see the snapshot below) helps automate the
% steps and provides a guided path from MATLAB to hardware. You can see the
% following key steps of the workflow in the left pane of the workflow
% advisor:
%
% # Fixed-Point Conversion
% # HDL Code Generation
% # HDL Verification
% # HDL Synthesis and Analysis
%
% <<hdlwfa.png>>
%
%
% Let's look at each workflow step in detail.
% 
% *Fixed-Point Conversion*
%
% Signal processing applications are typically implemented using
% floating-point operations in MATLAB. However, for power, cost, and
% performance reasons, these algorithms need to be converted to use
% fixed-point operations when targeting hardware. Fixed-point conversion
% can be very challenging and time-consuming, typically demanding 25 to 50
% percent of the total design and implementation time.  The automatic
% floating-point to fixed-point conversion workflow in HDL Coder(TM) can
% greatly simplify and accelerate this conversion process.
%
% The floating-point to fixed-point conversion workflow consists of the
% following steps:
%
% # Verify that the floating-point design is compatible with code
% generation.
% # Propose fixed-point types based on computed ranges, either through the
% simulation of the testbench or through static analysis that propagates
% design ranges to compute derived ranges for all the variables.
% # Generate fixed-point MATLAB code by applying proposed fixed-point
% types.
% # Verify the generated fixed-point code and compare the numerical
% accuracy of the generated fixed-point code with the original floating
% point code.
%
% Note that this step is optional. You can skip this step if your MATLAB
% design is already implemented in fixed-point.
%
% *HDL Code Generation*
%
% The HDL Code Generation step generates HDL code from the fixed-point
% MATLAB code. You can generate either VHDL or Verilog code that implements
% your MATLAB design. In addition to generating synthesizable HDL code, HDL
% Coder(TM) also generates various reports, including a traceability report
% that helps you navigate between your MATLAB code and the generated HDL
% code, and a resource utilization report that shows you, at the algorithm
% level, approximately what hardware resources are needed to implement the
% design, in terms of adders, multipliers, and RAMs.
%
% During code generation, you can specify various optimization options to
% explore the design space without having to modify your algorithm. In the
% Design Space Exploration and Optimization Options section below, you can
% see how you can modify code generation options and optimize your design
% for speed or area.
%
% *HDL Verification*
% 
% Standalone HDL test bench generation:
%
% HDL Coder(TM) generates VHDL and Verilog test benches from your MATLAB
% scripts for rapid verification of generated HDL code. You can customize
% an HDL test bench using a variety of options that apply stimuli to the
% HDL code. You can also generate script files to automate the process of
% compiling and simulating your code in HDL simulators. These steps help to
% ensure the results of MATLAB simulation match the results of HDL
% simulation.
%
% HDL Coder(TM) also works with
% <http://www.mathworks.com/products/hdl-verifier HDL Verifier> to
% automatically generate two types of cosimulation testbenches:
%
% * HDL cosimulation-based verification works with Mentor Graphics(R)
% ModelSim(R) and QuestaSim(R), where MATLAB and HDL simulation happen in
% lockstep.
% * FPGA-in-the-Loop simulation allows you to run a MATLAB simulation with
% an FPGA board in strict synchronization. You can use MATLAB to feed real
% world data into your design on the FPGA, and ensure that the algorithm
% will behave as expected when implemented in hardware.
%
% *HDL Synthesis*
%
% Apart from the language-related challenges, programming for FPGAs
% requires the use of complex EDA tools. Generating a bitstream from the
% HDL design and programming the FPGA can be daunting tasks. HDL Coder(TM)
% provides automation here, by creating project files for Xilinx(R) and
% Altera(R) that are configured with the generated HDL code. You can use
% the workflow steps to synthesize the HDL code within the MATLAB
% environment, see the results of synthesis, and iterate on the MATLAB
% design to improve synthesis results.

%% Design Space Exploration and Optimization Options
% HDL Coder(TM) provides the following optimizations to help you explore
% the design space trade-offs between area and speed. You can use these
% options to explore various architectures and trade-offs without having to
% manually rewrite your algorithm.
%
% *Speed Optimizations*
%
% * *Pipelining* : To improve the designâ€™s clock frequency, HDL Coder
% enables you to insert pipeline registers in various locations within your
% design. For example, you can insert registers at the design inputs and
% outputs, and also at the output of a given MATLAB variable in your
% algorithm.
% * *Distributed Pipelining* : HDL Coder also provides an optimization
% based on retiming to automatically move pipeline registers you have
% inserted to maximize clock frequency, by minimizing the delay through
% combinational paths in your design.
%
%
% *Area Optimizations*
%
% * *RAM mapping*: HDL Coder(TM) maps matrices to wires or registers in
% hardware. If persistent matrix variables are mapped to registers, they
% can take up a large amount of FPGA area. HDL Coder(TM) automatically maps
% persistent matrices to block RAM to improve area efficiency. The
% challenge in mapping MATLAB matrices to block RAM is that block RAM in
% hardware typically has a limited set of read and write ports. HDL
% Coder(TM) solves this problem by automatically partitioning and
% scheduling the matrix reads and writes to honor the block RAMâ€™s port
% constraints, while still honoring the other control- and
% data-dependencies in the design.
% * *Resource sharing*: This optimization identifies functionally
% equivalent multiplier operations in MATLAB code and shares them. You can
% control the amount of multiplier sharing in the design.
% * *Loop streaming*: A MATLAB for-loop creates a FOR_GENERATE loop in
% VHDL. The body of the loop is replicated as many times in hardware as the
% number of loop iterations. This results in an inefficient use of area.
% The loop streaming optimization creates a single hardware instance of the
% loop body that is time-multiplexed across loop iterations.
% * *Constant multiplier optimization*: This design level optimization
% converts constant multipliers into shift and add operations using
% canonical signed digit (CSD) techniques.
%

%% Best Practices
% Now, let's look at few best practices related to writing MATLAB code when
% targeting FPGAs.
%
% *When writing a MATLAB design:*
%
% * Use the code generation subset of MATLAB supported for HDL code
% generation.
% * Keep the top-level interface as simple as possible. The top-level
% function size, types, and complexity determine the interface of the chip
% implemented in hardware.
% * Do not pass in a big chunk of parallel data into the design. Parallel
% data requires a large number of IO pins on the chip, and would probably
% not be synthesizable.  In a typical image processing design, you should
% serialize the pixels as inputs and buffer them internally in the
% algorithm.
%
% *When writing a MATLAB test bench:*
%
% * Call the design from the testbench function.
% * Exercise the design thoroughly. This is particularly important for
% floating-point to fixed-point conversion, where HDL Coder(TM) determines
% the ranges of the variables in the algorithm based on the values the
% testbench assigns to the variables. You can reuse this testbench to
% generate an HDL testbench for testing the generated hardware.
% * Simulate the design with the testbench prior to code generation to make
% sure there are no simulation errors, and to make sure all the required
% files are on the path.

%% Conclusion
% HDL Coder(TM) provides a seamless workflow when you want to implement
% your algorithm in an FPGA. In this post, I have shown you how to take an
% image processing algorithm written in MATLAB, convert it to fixed-point,
% generate HDL code, verify the generated HDL code using the test bench,
% and finally, synthesize the design and implement it in hardware.
%
% See this
% <http://www.mathworks.com/company/newsroom/FLIR-Speeds-Thermal-Imaging-FPGA-Development-Through-Automatic-HDL-Generation-From-MATLAB.html
% article> about how one of the HDL Coder customers, FLIR has used MATLAB
% to HDL workflow to achieve good results. You can also learn more about
% this workflow using the product examples
% <http://www.mathworks.com/products/hdl-coder/examples.html located here.>
%
% We hope this brief introduction to the HDL Coder(TM) and MATLAB-to-HDL
% code generation, verification framework has shown how you can quickly get
% started on implementing your MATLAB designs and target FPGAs. Please let
% us know in the comments for this post how you might use this new
% functionality. Or, if you've already tried using HDL Coder(TM), let us
% know about your experiences
% <http://blogs.mathworks.com/loren/?p=673#respond here>.
%
##### SOURCE END ##### 62189eb44b6e46ffafdbf080e751390b
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/kOoWp0H4zmg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/04/11/matlab-to-fpga-using-hdl-codertm/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/04/11/matlab-to-fpga-using-hdl-codertm/</feedburner:origLink></item>
		<item>
		<title>New Datatype under Development for Possible MATLAB Release</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/y_pNDxHc1QY/</link>
		<comments>http://blogs.mathworks.com/loren/2013/04/01/new-datatype-under-development-for-possible-matlab-release/#comments</comments>
		<pubDate>Mon, 01 Apr 2013 13:14:09 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Fun]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=655</guid>
		<description><![CDATA[There is a new datatype we are playing around with that we hope to make available in an upcoming release and we would like your input beforehand.ContentsNew Datatype in ActionLet's Examine the OutputShould We Invest More Resources?New Datatype in ActionLet me show you the new datatype in action so you can first get a feel [...]]]></description>
				<content:encoded><![CDATA[
<div class="content"><!--introduction--><p>There is a new datatype we are playing around with that we hope to make available in an upcoming release and we would like your input beforehand.</p><!--/introduction--><h3>Contents</h3><div><ul><li><a href="#0db87324-2965-4901-8815-a6971dc0e459">New Datatype in Action</a></li><li><a href="#b3bda645-6f1d-4c77-9b0f-97bded4ae828">Let's Examine the Output</a></li><li><a href="#d2c273a6-73dd-4ef1-875b-086b90250ba3">Should We Invest More Resources?</a></li></ul></div><h4>New Datatype in Action<a name="0db87324-2965-4901-8815-a6971dc0e459"></a></h4><p>Let me show you the new datatype in action so you can first get a feel for it.</p><pre class="codeinput">inputData = magic(3)
</pre><pre class="codeoutput">inputData =
     8     1     6
     3     5     7
     4     9     2
</pre><pre class="codeinput">outputValues = dis(inputData);
</pre><h4>Let's Examine the Output<a name="b3bda645-6f1d-4c77-9b0f-97bded4ae828"></a></h4><pre class="codeinput">outputValues
</pre><pre class="codeoutput">Why are you asking?
     4     2     3
     1     9     6
     8     7     5
</pre><p>Well, that's a bit strange, isn't it?  I wonder what the relationship between <tt>inputData</tt> and <tt>outputValues</tt> is.  What can we learn about <tt>outputValues</tt>?</p><pre class="codeinput">whos <span class="string">outputValues</span>
</pre><pre class="codeoutput">  Name              Size            Bytes  Class    Attributes

  outputValues      1x1               248  dis                

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


</pre><h4>Should We Invest More Resources?<a name="d2c273a6-73dd-4ef1-875b-086b90250ba3"></a></h4><p>Of course, I could also add some numeric functions like <tt>plus</tt> to <tt>dis</tt>, but I didn't take the time, in case you didn't find this possible new MATLAB addition useful. So please share your thoughts with us <a href="http://blogs.mathworks.com/loren/?p=655#respond">here</a>.</p><script language="JavaScript"> <!-- 
    function grabCode_a181c2e627784116bd2a8279503e14c9() {
        // 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='a181c2e627784116bd2a8279503e14c9 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' a181c2e627784116bd2a8279503e14c9';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_a181c2e627784116bd2a8279503e14c9()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><!--
a181c2e627784116bd2a8279503e14c9 ##### SOURCE BEGIN #####
%% New Datatype under Development for Possible MATLAB Release
% There is a new datatype we are playing around with that we hope to make
% available in an upcoming release and we would like your input beforehand.
%% New Datatype in Action
% Let me show you the new datatype in action so you can first get a feel
% for it.
inputData = magic(3)
%%
outputValues = dis(inputData);
%% Let's Examine the Output
outputValues
%%
% Well, that's a bit strange, isn't it?  I wonder what the relationship
% between |inputData| and |outputValues| is.  What can we learn about
% |outputValues|?
whos outputValues
%%
% Well, it's a |dis| array.  Let's look at it again.
outputValues
%% 
% Say what?  Let's check it a few more times.
outputValues
outputValues
outputValues
%% 
% Hoping you get the double meaning here - the |dis| array not only mixes
% up the values of the input for display purposes, but also tries to gently
% *dis*respect you along the way.  
%%
% Even though this is a silly class, I'll show you the code so you can see
% how simple it is to make such a class.
type dis
%% Should We Invest More Resources?
% Of course, I could also add some numeric functions like |plus| to |dis|,
% but I didn't take the time, in case you didn't find this possible new
% MATLAB addition useful. So please share your thoughts with us
% <http://blogs.mathworks.com/loren/?p=655#respond here>.
##### SOURCE END ##### a181c2e627784116bd2a8279503e14c9
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/y_pNDxHc1QY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/04/01/new-datatype-under-development-for-possible-matlab-release/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/04/01/new-datatype-under-development-for-possible-matlab-release/</feedburner:origLink></item>
		<item>
		<title>Multiple Y Axes</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/27LIZTZvD7o/</link>
		<comments>http://blogs.mathworks.com/loren/2013/03/27/multiple-y-axes/#comments</comments>
		<pubDate>Wed, 27 Mar 2013 19:42:07 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Graphics]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=665</guid>
		<description><![CDATA[We were musing here about how common it is to want more than two Y axes on a plot. Checking out the File Exchange, there seem to be several candidates, indicating that this is something at least some people find useful.ContentsSample PlotList of Some PossibilitiesWhat are You Plotting with More Y Axes?Sample PlotHere's a sample [...]]]></description>
				<content:encoded><![CDATA[
<div class="content"><!--introduction--><p>We were musing here about how common it is to want more than two Y axes on a plot.  Checking out the File Exchange, there seem to be several candidates, indicating that this is something at least some people find useful.</p><!--/introduction--><h3>Contents</h3><div><ul><li><a href="#708b44b8-5fb8-446f-92c3-5a7356e4ab5d">Sample Plot</a></li><li><a href="#3b58211f-2b7e-484d-952e-5e8fffa5f81c">List of Some Possibilities</a></li><li><a href="#8c4f04ed-9976-4594-92c5-c77284c345fe">What are You Plotting with More Y Axes?</a></li></ul></div><h4>Sample Plot<a name="708b44b8-5fb8-446f-92c3-5a7356e4ab5d"></a></h4><p>Here's a sample plot using <tt>plotyy</tt> that comes with MATLAB.</p><pre class="codeinput">x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
plotyy(x,y1,x,y2,<span class="string">'plot'</span>);
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/plotyyFEX_01.png" alt=""> <h4>List of Some Possibilities<a name="3b58211f-2b7e-484d-952e-5e8fffa5f81c"></a></h4><p>In addition to <tt>plotyy</tt> in MATLAB, here's a list of <i>some</i> of the candidates from the File Exchange.</p><div><ul><li><a href="http://www.mathworks.com/matlabcentral/fileexchange/9016"> <tt>addaxis</tt></a></li><li><a href="http://www.mathworks.com/matlabcentral/fileexchange/4425-ploty4-m"><tt>plot4y</tt></a></li><li><a href="http://www.mathworks.com/matlabcentral/fileexchange/26550-myplotyy"><tt>Myplotyy</tt></a></li><li><a href="http://www.mathworks.com/matlabcentral/fileexchange/1017-plotyyy"><tt>plotyyy</tt></a></li><li><a href="http://www.mathworks.com/matlabcentral/fileexchange/10242-plots-m-plotses-m"><tt>plots.m plotses.m</tt></a></li><li><a href="http://www.mathworks.com/matlabcentral/fileexchange/39595-multiplotyyy"><tt>multiplotyyy</tt></a></li></ul></div><h4>What are You Plotting with More Y Axes?<a name="8c4f04ed-9976-4594-92c5-c77284c345fe"></a></h4><p>I am curious to know what kind of data or results you are plotting so that having multiple y-axes makes a compelling presentation.  Let us know <a href="http://blogs.mathwoks.com/p=665#respond">here</a>.</p><script language="JavaScript"> <!-- 
    function grabCode_79a95834e135447399e4a186bba57f16() {
        // 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='79a95834e135447399e4a186bba57f16 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 79a95834e135447399e4a186bba57f16';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_79a95834e135447399e4a186bba57f16()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><!--
79a95834e135447399e4a186bba57f16 ##### SOURCE BEGIN #####
%% Multiple Y Axes
% We were musing here about how common it is to want more than two Y axes
% on a plot.  Checking out the File Exchange, there seem to be several
% candidates, indicating that this is something at least some people find
% useful.

%% Sample Plot
% Here's a sample plot using |plotyy| that comes with MATLAB.
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
plotyy(x,y1,x,y2,'plot');

%% List of Some Possibilities
% In addition to |plotyy| in MATLAB, here's a list of _some_ of the
% candidates from the File Exchange.
%
% * <http://www.mathworks.com/matlabcentral/fileexchange/9016  |addaxis|>
% * <http://www.mathworks.com/matlabcentral/fileexchange/4425-ploty4-m
% |plot4y|>
% * <http://www.mathworks.com/matlabcentral/fileexchange/26550-myplotyy |Myplotyy|>
% * <http://www.mathworks.com/matlabcentral/fileexchange/1017-plotyyy
% |plotyyy|>
% * <http://www.mathworks.com/matlabcentral/fileexchange/10242-plots-m-plotses-m
% |plots.m plotses.m|>
% * <http://www.mathworks.com/matlabcentral/fileexchange/39595-multiplotyyy
% |multiplotyyy|>
%% What are You Plotting with More Y Axes?
% I am curious to know what kind of data or results you are plotting so
% that having multiple y-axes makes a compelling presentation.  Let us know
% <http://blogs.mathwoks.com/p=665#respond here>.

##### SOURCE END ##### 79a95834e135447399e4a186bba57f16
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/27LIZTZvD7o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/03/27/multiple-y-axes/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/03/27/multiple-y-axes/</feedburner:origLink></item>
		<item>
		<title>Using the MATLAB Unit Testing Infrastructure for Grading Assignments</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/nkzH_P-RoGo/</link>
		<comments>http://blogs.mathworks.com/loren/2013/03/14/using-the-matlab-unit-testing-infrastructure-for-grading-assignments/#comments</comments>
		<pubDate>Thu, 14 Mar 2013 15:18:23 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[New Feature]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=649</guid>
		<description><![CDATA[Steven Lord, Andy Campbell, and David Hruska are members of the Quality Engineering group at MathWorks who are guest blogging today to introduce a new feature in R2013a, the MATLAB unit testing infrastructure. There are several submissions on the MATLAB Central File Exchange related to unit testing of MATLAB code. Blogger Steve Eddins wrote one [...]]]></description>
				<content:encoded><![CDATA[
<div class="content"><!--introduction--><p>Steven Lord, Andy Campbell, and David Hruska are members of the Quality Engineering group at MathWorks who are guest blogging today to introduce a new feature in R2013a, the MATLAB unit testing infrastructure. There are several submissions on the MATLAB Central File Exchange related to unit testing of <tt>MATLAB</tt> code. Blogger Steve Eddins wrote one highly rated <a href="http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework">example</a> back in 2009. In release R2013a, MathWorks included in <tt>MATLAB</tt> itself a <tt>MATLAB</tt> implementation of the industry-standard xUnit testing framework.</p><p>If you're not a software developer, you may be wondering if this feature will be of any use to you. In this post, we will describe one way someone who may not consider themselves a software developer may be able to take advantage of this framework using the example of a professor grading students' homework submissions. That's not to say that the developers in the audience should move on to the next post; you can use these tools to test your own code just like a professor can use them to test code written by his or her students.</p><p>There is a great deal of functionality in this feature that we will not show here. For more information we refer you to the <a href="http://www.mathworks.com/help/matlab/matlab-unit-test-framework.html">MATLAB Unit Testing Framework</a> documentation.</p><!--/introduction--><h3>Contents</h3><div><ul><li><a href="#454b2d47-cbbb-48bf-b2ba-50c3891d7f7a">Background</a></li><li><a href="#a7a02684-3047-424b-a927-3b218f015807">Problem Statement</a></li><li><a href="#eeac7ca5-eb4b-4028-9a87-c969cd27c754">Basic Unit Test</a></li><li><a href="#23717901-ce74-47ed-9564-08b52b69c2a4">Running a Test</a></li><li><a href="#8cf80ad8-6ac6-4606-951c-441a8ba5bcd7">Test that F(0) Equals 1</a></li><li><a href="#15df7917-0f94-4a3f-b915-552df373e33f">Test that F(pi) Throws an Error</a></li><li><a href="#3ad5bde5-93a3-4204-b976-8a60edad5fc6">Basic Test for Students, Advanced Tests for Instructor</a></li><li><a href="#b8d2ed9f-3356-4308-bc9b-b269f74b93bd">Conclusion</a></li></ul></div><h4>Background<a name="454b2d47-cbbb-48bf-b2ba-50c3891d7f7a"></a></h4><p>In order to use this feature, you should be aware of how to define simple <tt>MATLAB</tt> classes in <i>classdef</i> files, how to define a class that inherits from another, and how to specify attributes for methods and properties of those classes. The <a href="http://www.mathworks.com/help/matlab/object-oriented-programming.html">object-oriented programming</a> documentation describes these capabilities.</p><h4>Problem Statement<a name="a7a02684-3047-424b-a927-3b218f015807"></a></h4><p>As a professor in an introductory programming class, you want your students to write a program to compute Fibonacci numbers. The exact problem statement you give the students is:</p><pre>Create a function "fib" that accepts a nonnegative integer n and returns
the nth Fibonacci number. The Fibonacci numbers are generated by this
relationship:</pre><pre>F(0) = 1
F(1) = 1
F(n) = F(n-1) + F(n-2) for integer n &gt; 1</pre><pre>Your function should throw an error if n is not a nonnegative integer.</pre><h4>Basic Unit Test<a name="eeac7ca5-eb4b-4028-9a87-c969cd27c754"></a></h4><p>The most basic <tt>MATLAB</tt> unit test is a <tt>MATLAB</tt> <i>classdef</i> class file that inherits from the <tt>matlab.unittest.TestCase</tt> class. Throughout the rest of this post we will add additional pieces to this basic framework to increase the capability of this test and will change its name to reflect its increased functionality.</p><pre class="codeinput">dbtype <span class="string">basicTest.m</span>
</pre><pre class="codeoutput">
1     classdef basicTest &lt; matlab.unittest.TestCase
2         
3     end
</pre><pre class="codeinput">test = basicTest
</pre><pre class="codeoutput">test = 
  basicTest with no properties.
</pre><h4>Running a Test<a name="23717901-ce74-47ed-9564-08b52b69c2a4"></a></h4><p>To run the test, we can simply pass <tt>test</tt> to the <tt>run</tt> function. There are more advanced ways that make it easier to run a group of tests, but for our purposes (checking one student's answer at a time) this will be sufficient. When you move to checking multiple students' answers at a time, you can use <tt>run</tt> inside a <tt>for</tt> loop.</p><p>Since <tt>basicTest</tt> doesn't actually validate the output from the student's function, it doesn't take very long to execute.</p><pre class="codeinput">results = run(test)
</pre><pre class="codeoutput">results = 
  0x0 TestResult array with properties:

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

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

results = 
  TestResult with properties:

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

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

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

Failure Summary:

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

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

results = 
  1x2 TestResult array with properties:

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

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

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

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

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

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

Failure Summary:

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

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

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

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

results = 
  1x3 TestResult array with properties:

    Name
    Passed
    Failed
    Incomplete
    Duration
Totals:
   3 Passed, 0 Failed, 0 Incomplete.
   0.015946 seconds testing time.
100% Passed.
</pre><h4>Conclusion<a name="b8d2ed9f-3356-4308-bc9b-b269f74b93bd"></a></h4><p>In this post, we showed you the basics of using the new MATLAB unit testing infrastructure using homework grading as a use case.</p><p>We checked that the student's code worked (by returning the correct answer) for one valid value and worked (by throwing an error) for one invalid value. We also showed how you can use this infrastructure to provide an aid/check for the students that you can also use as part of your grading.</p><p>We hope this brief introduction to the unit testing framework has shown you how you can make use of this feature even if you don't consider yourself a software developer. Let us know in the comments for this post how you might use this new functionality. Or, if you've already tried using matlab.unittest, let us know about your experiences <a href="http://blogs.mathworks.com/loren/?p=649#respond">here</a>.</p><script language="JavaScript"> <!-- 
    function grabCode_ab73aa9d90954425ba64e5af0214ae47() {
        // 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='ab73aa9d90954425ba64e5af0214ae47 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' ab73aa9d90954425ba64e5af0214ae47';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_ab73aa9d90954425ba64e5af0214ae47()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2013a<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2013a<br /></p></div><!--
ab73aa9d90954425ba64e5af0214ae47 ##### SOURCE BEGIN #####
%% Using the MATLAB Unit Testing Infrastructure for Grading Assignments
% Steven Lord, Andy Campbell, and David Hruska are members of the Quality
% Engineering group at MathWorks who are guest blogging today to introduce
% a new feature in R2013a, the MATLAB unit testing infrastructure. There
% are several submissions on the MATLAB Central File Exchange related to
% unit testing of |MATLAB| code. Blogger Steve Eddins wrote one highly
% rated
% <http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework
% example> back in 2009. In release R2013a, MathWorks included in |MATLAB|
% itself a |MATLAB| implementation of the industry-standard xUnit testing
% framework.
%
% If you're not a software developer, you may be wondering if this feature
% will be of any use to you. In this post, we will describe one way someone
% who may not consider themselves a software developer may be able to take
% advantage of this framework using the example of a professor grading
% students' homework submissions. That's not to say that the developers in
% the audience should move on to the next post; you can use these tools to
% test your own code just like a professor can use them to test code
% written by his or her students.
%
% There is a great deal of functionality in this feature that we will not
% show here. For more information we refer you to the
% <http://www.mathworks.com/help/matlab/matlab-unit-test-framework.html
% MATLAB Unit Testing Framework> documentation.

%% Background
% In order to use this feature, you should be aware of how to define simple
% |MATLAB| classes in _classdef_ files, how to define a class that inherits
% from another, and how to specify attributes for methods and properties of
% those classes. The
% <http://www.mathworks.com/help/matlab/object-oriented-programming.html
% object-oriented programming> documentation describes these capabilities.

%% Problem Statement
% As a professor in an introductory programming class, you want your
% students to write a program to compute Fibonacci numbers. The exact
% problem statement you give the students is:
%
%  Create a function "fib" that accepts a nonnegative integer n and returns
%  the nth Fibonacci number. The Fibonacci numbers are generated by this
%  relationship:
%
%  F(0) = 1
%  F(1) = 1
%  F(n) = F(n-1) + F(n-2) for integer n > 1
%
%  Your function should throw an error if n is not a nonnegative integer.

%% Basic Unit Test
% The most basic |MATLAB| unit test is a |MATLAB| _classdef_ class file
% that inherits from the |matlab.unittest.TestCase| class. Throughout the
% rest of this post we will add additional pieces to this basic framework to
% increase the capability of this test and will change its name to reflect
% its increased functionality.
dbtype basicTest.m

%%
test = basicTest

%% Running a Test
% To run the test, we can simply pass |test| to the |run| function. There
% are more advanced ways that make it easier to run a group of tests, but
% for our purposes (checking one student's answer at a time) this will be
% sufficient. When you move to checking multiple students' answers at a
% time, you can use |run| inside a |for| loop.
%
% Since |basicTest| doesn't actually validate the output from the student's
% function, it doesn't take very long to execute.
results = run(test)

%%
% Let's say that a student named Thomas submitted a function |fib.m| as his
% solution to this assignment. Thomas's code is stored in a sub-folder
% named |thomas|. To set up our test to check Thomas's answer, we add the
% folder holding his code to the path.
addpath('thomas');
dbtype fib.m


%% Test that F(0) Equals 1
% The |basicTest| is a valid test class, and we can run it, but it doesn't
% actually perform any validation of the student's test file. The methods
% that will perform that validation need to be written in a _methods_ block
% that has the attribute |Test| specified.
%
% The |matlab.unittest.TestCase| class includes qualification methods that
% you can use to test various qualities of the results returned by the
% student files. The qualification method that you will likely use most
% frequently is the |verifyEqual| method, which passes if the two values
% you pass into it are equal and reports a test failure if they are not.
%
% The
% <http://www.mathworks.com/help/matlab/ref/matlab.unittest.testcaseclass.html
% documentation> for the |matlab.unittest.TestCase| class lists many other
% qualification methods that you can use to perform other types of
% validation, including testing the data type and size of the results;
% matching a string result to an expected string; testing that a given
% section of code throws a specific errors or issues a specific warning;
% and many more.
%
% This simple test builds upon |generalTest| by adding a test method that
% checks that the student's function returns the value 1 when called with
% the input 0.
dbtype simpleTest.m

%% 
% Thomas's solution to the assignment satisfies this basic check. We can
% use the results returned from |run| to display the percentage of the
% tests that pass.
results = run(simpleTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

%% Test that F(pi) Throws an Error
% Now that we have a basic positive test in place we can add in a test that
% checks the behavior of the student's function when passed a non-integer
% value (like |n = pi|) as input. The assignment stated that when called
% with a non-integer value, the student's function should error. Since the
% assignment doesn't require a specific error to be thrown, the test passes
% as long as |fib(pi)| throws any exception.
dbtype errorCaseTest.m

%%
% Thomas forgot to include a check for a non-integer valued input in his
% function, so our test should indicate that by reporting a failure.
results = run(errorCaseTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

%%
% Another student, Benjamin, checked for a non-integer value in his code as
% you can see on line 2.
rmpath('thomas');
addpath('benjamin');
dbtype fib.m

%% 
% Benjamin's code passed both the test implemented in the
% |fibonacciOfZeroShouldBeOne| method (which we copied into |errorCaseTest|
% from |simpleTest|) and the new test case implemented in the
% |fibonacciOfNonintegerShouldError| method.
results = run(errorCaseTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

%% Basic Test for Students, Advanced Tests for Instructor
% The problem statement given earlier in this post is a plain text
% description of the homework assignment we assigned to the students. We
% can also state the problem for the students in code (if they're using
% release R2013a or later) by giving them a test file they can run just
% like |simpleTest| or |errorCaseTest|. They can directly use this
% "requirement test" to ensure their functions satisfy the requirements of
% the assignment.
dbtype studentTest.m

%%
% In order for the student's code to pass the assignment, it will need to
% pass the test cases given in the |studentTest| unit test. However, we
% don't want to use |studentTest| as the _only_ check of the student's
% code. If we did, the student could write their function to cover only the
% test cases in the student test file.
%
% We could solve this problem by having two separate test files, one
% containing the student test cases and one containing additional test
% cases the instructor uses in the grading process. Can we avoid having to
% run both test files manually or duplicating the code from the student
% test cases in the instructor test? Yes!
%
% To do so, we write an instructor test file to incorporate, through
% inheritance, the student test file. We can then add additional test
% cases to the instructor test file. When we run this test it should run
% three test cases; two inherited from |studentTest|,
% |fibonacciOfZeroShouldBeOne| and |fibonacciOfNonintegerShouldError|, and
% one from |instructorTest| itself, |fibonacciOf5|.
dbtype instructorTest.m

%%
% Let's look at Eric's test file that passes the
% |studentTestFile| test, but in which he completely forgot to implement
% the |F(n) = F(n-1)+F(n-2)| recursion step.
rmpath('benjamin');
addpath('eric');
dbtype fib.m

%%
% It should pass the student unit test.
results = run(studentTest);
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

%% 
% It does NOT pass the instructor unit test because it fails one of the
% test cases.
results = run(instructorTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

%%
% Benjamin, whose code we tested above, wrote a correct solution to the
% homework problem.
rmpath('eric');
addpath('benjamin');

results = run(instructorTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

rmpath('benjamin');

%% Conclusion
% In this post, we showed you the basics of using the new MATLAB unit
% testing infrastructure using homework grading as a use case.
%
% We checked that the student's code worked (by returning the correct
% answer) for one valid value and worked (by throwing an error) for one
% invalid value. We also showed how you can use this infrastructure to
% provide an aid/check for the students that you can also use as part of
% your grading.
%
% We hope this brief introduction to the unit testing framework has shown
% you how you can make use of this feature even if you don't consider
% yourself a software developer. Let us know in the comments for this post
% how you might use this new functionality. Or, if you've already tried
% using matlab.unittest, let us know about your experiences
% <http://blogs.mathworks.com/loren/?p=649#respond here>.
##### SOURCE END ##### ab73aa9d90954425ba64e5af0214ae47
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/nkzH_P-RoGo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/03/14/using-the-matlab-unit-testing-infrastructure-for-grading-assignments/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/03/14/using-the-matlab-unit-testing-infrastructure-for-grading-assignments/</feedburner:origLink></item>
		<item>
		<title>Major New Release at Chebfun – Two Dimensional Capabilities</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/OR8K3v-7o9U/</link>
		<comments>http://blogs.mathworks.com/loren/2013/03/06/major-new-release-at-chebfun-two-dimensional-capabilities/#comments</comments>
		<pubDate>Wed, 06 Mar 2013 14:25:46 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[Fun]]></category>
		<category><![CDATA[New Feature]]></category>
		<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=643</guid>
		<description><![CDATA[Perhaps you've read about Chebfun before here or on Cleve''s blog. Chebfun allows you to do numerical computing with functions and not simply numbers. If not, you might want to investigate. If so, you may be very interested in new capabilities available.ContentsMajor New CapabilityMany ExamplesMajor New CapabilityJust recently, the Chebfun team released a major new [...]]]></description>
				<content:encoded><![CDATA[
<div class="content"><!--introduction--><p>Perhaps you've read about <a href="http://www2.maths.ox.ac.uk/chebfun/">Chebfun</a> before <a href="http://blogs.mathworks.com/loren/2011/06/21/update-on-the-chebfun-project/">here</a> or on <a href="http://blogs.mathworks.com/cleve/2012/10/01/chebfun-numerical-computing-with-functions/">Cleve''s blog</a>.  Chebfun allows you to do numerical computing with functions and not simply numbers.  If not, you might want to investigate. If so, you may be very interested in new capabilities available.</p><!--/introduction--><h3>Contents</h3><div><ul><li><a href="#2cc21f9d-c30a-4db0-a793-5f05df419544">Major New Capability</a></li><li><a href="#ad6aad99-6990-4336-b8ee-1f335655af29">Many Examples</a></li></ul></div><h4>Major New Capability<a name="2cc21f9d-c30a-4db0-a793-5f05df419544"></a></h4><p>Just recently, the Chebfun team released a major new capability on their site.  While Chebfun is extremely useful, it was restricted to solving problems in one dimension.  Now you may solve problems with two independent variables using <a href="http://www2.maths.ox.ac.uk/chebfun/chebfun2/">Chebfun2</a>! As before, their website includes code you can freely download and many interesting examples.  The examples are well documented and easy to learn from.  I will soon have time to explore Chebfun2 because of an irrational amount of airline time.</p><p>I also love how easy it is to install - you can do it from MATLAB. They kindly post the code right on the website so you can paste it into your running session.</p><h4>Many Examples<a name="ad6aad99-6990-4336-b8ee-1f335655af29"></a></h4><p>They have many examples included in the software, and posted on their web site, using the <a href="http://www.mathworks.com/help/matlab/ref/publish.html"><tt>publish</tt></a> command in MATLAB.  The high-level examples are organized into these categories:</p><div><ol><li>Approximation</li><li>Complex Analysis</li><li>Geometry</li><li>Optimization</li><li>Statistics</li><li>Rootfinding</li><li>Vector Calculus</li><li>Fun !</li></ol></div><p>I hope with this breadth of examples, you are able to find ones interesting or relevant (or both) to you.  Once you've gotten a chance to try out Chebfun2, I'd love to hear about your experiences.  Post them <a href="blogs.mathworks.com/loren/?p=643#respond">here</a> to share with us.</p><script language="JavaScript"> <!-- 
    function grabCode_e9cedf5b474c429390024f2f5d4e51d2() {
        // 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='e9cedf5b474c429390024f2f5d4e51d2 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' e9cedf5b474c429390024f2f5d4e51d2';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_e9cedf5b474c429390024f2f5d4e51d2()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><!--
e9cedf5b474c429390024f2f5d4e51d2 ##### SOURCE BEGIN #####
%% Major New Release at Chebfun - Two Dimensional Capabilities
% Perhaps you've read about <http://www2.maths.ox.ac.uk/chebfun/ Chebfun>
% before
% <http://blogs.mathworks.com/loren/2011/06/21/update-on-the-chebfun-project/
% here> or on
% <http://blogs.mathworks.com/cleve/2012/10/01/chebfun-numerical-computing-with-functions/
% Cleve''s blog>.  Chebfun allows you to do numerical computing with
% functions and not simply numbers.  If not, you might want to investigate.
% If so, you may be very interested in new capabilities available.
%% Major New Capability
% Just recently, the Chebfun team released a major new capability on their
% site.  While Chebfun is extremely useful, it was restricted to solving
% problems in one dimension.  Now you may solve problems with two
% independent variables using <http://www2.maths.ox.ac.uk/chebfun/chebfun2/
% Chebfun2>! As before, their website includes code you can freely download
% and many interesting examples.  The examples are well documented and easy
% to learn from.  I will soon have time to explore Chebfun2 because of an
% irrational amount of airline time.
%%
% I also love how easy it is to install - you can do it from MATLAB. They
% kindly post the code right on the website so you can paste it into your
% running session.
%% Many Examples
% They have many examples included in the software, and posted on their web
% site, using the <http://www.mathworks.com/help/matlab/ref/publish.html
% |publish|> command in MATLAB.  The high-level examples are organized into
% these categories:
%
% # Approximation
% # Complex Analysis
% # Geometry
% # Optimization
% # Statistics
% # Rootfinding
% # Vector Calculus
% # Fun !
%
%%
% I hope with this breadth of examples, you are able to find ones
% interesting or relevant (or both) to you.  Once you've gotten a chance to
% try out Chebfun2, I'd love to hear about your experiences.  Post them
% <blogs.mathworks.com/loren/?p=643#respond here> to share with us.



##### SOURCE END ##### e9cedf5b474c429390024f2f5d4e51d2
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/OR8K3v-7o9U" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/03/06/major-new-release-at-chebfun-two-dimensional-capabilities/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/03/06/major-new-release-at-chebfun-two-dimensional-capabilities/</feedburner:origLink></item>
		<item>
		<title>Logical Indexing – Multiple Conditions</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/LddjaaOsw6M/</link>
		<comments>http://blogs.mathworks.com/loren/2013/02/20/logical-indexing-multiple-conditions/#comments</comments>
		<pubDate>Wed, 20 Feb 2013 13:48:52 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Indexing]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=637</guid>
		<description><![CDATA[I've talked about logical indexing before in some of the linked posts, but recent work makes me want to show it off again. One of the nice things about logical indexing is that it is very easy and natural to combine the results of different conditions to select items based on multiple criteria.ContentsWhat is Logical [...]]]></description>
				<content:encoded><![CDATA[<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<style type="text/css">

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

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

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

@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }

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

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

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

  logInd      1x20               20  logical              

</pre><p>I can now use this array to extract the desired values from <tt>X</tt>.</p><pre class="codeinput">XtargetLogical = X(logInd)
</pre><pre class="codeoutput">XtargetLogical =
     3     1     4     2
</pre><p>Both methods return the results.</p><pre class="codeinput">isequal(Xtarget, XtargetLogical)
</pre><pre class="codeoutput">ans =
     1
</pre><h4>Compound conditions.<a name="ef412173-88ef-43d1-81ab-b2df3d7dde77"></a></h4><p>Let me create an anonymous function that returns true (<tt>logical(1)</tt>) for values that are even integers.</p><pre class="codeinput">iseven = @(x) ~logical(rem(x,2))
</pre><pre class="codeoutput">iseven = 
    @(x)~logical(rem(x,2))
</pre><p>Test <tt>iseven</tt>.</p><pre class="codeinput">iseven(1:5)
</pre><pre class="codeoutput">ans =
     0     1     0     1     0
</pre><h4>Find Values Meeting More Than One Condition<a name="f4e56162-08ec-44b0-a4e8-7086976be875"></a></h4><p>Now I would like to find the values in <tt>X</tt> that are less than <tt>target</tt> and are even. This is very natural to do with logical indexing.  We have the pieces of code we need already.</p><pre class="codeinput">compoundCondInd = (X &lt; target) &amp; iseven(X)
</pre><pre class="codeoutput">compoundCondInd =
  Columns 1 through 13
     0     0     0     0     0     0     0     0     0     0     0     0     0
  Columns 14 through 20
     1     0     0     0     0     0     1
</pre><p>We can see we found suitable values at locations 3 and 19.  And we can extract those values next.</p><pre class="codeinput">X(compoundCondInd)
</pre><pre class="codeoutput">ans =
     4     2
</pre><h4>Did You Notice?<a name="a554527a-320f-40bd-95dc-42695925b486"></a></h4><p>Did you see how easy it is to combine multiple conditions?  I simply look for each of condition, getting back logical arrays, and then compute a logical array where the two input arrays are both true (via <tt>&amp;</tt>). I could, of course, calculate a compound condition where only either one or the other condition needs to be true using logical or (via |).</p><h4>A Recent Application<a name="e9531c73-0182-4f21-8bf5-c11a0970562d"></a></h4><p>I recently used this in the context of finding suspect data values.  I had 2 arrays, hourly temperature and speed.  The problem is that when the temperature gets near or below freezing, the speed sensor might freeze. But I didn't want to delete ALL the values below freezing.  So I looked for data where the temperature was sufficiently low AND the speed was very low (which could potentially mean the sensor was frozen).  That way, I did not need to discard all data at low temperatures.</p><h4>Have You Used Compound Indexing?<a name="14ef4d77-81f6-4722-a6ce-3cd56ca4d31b"></a></h4><p>Did you do it like I did, using logical expressions?  Or did you use some other techniques?  What were you trying to achieve with your compound indexing?  Let me know <a href="http://blogs.mathworks.com/loren/?p=637#respond">here</a>.</p><script language="JavaScript"> <!-- 
    function grabCode_bc94e2aee9fb45b9b09b65745fcb27fb() {
        // 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='bc94e2aee9fb45b9b09b65745fcb27fb ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' bc94e2aee9fb45b9b09b65745fcb27fb';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_bc94e2aee9fb45b9b09b65745fcb27fb()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><!--
bc94e2aee9fb45b9b09b65745fcb27fb ##### SOURCE BEGIN #####
%% Logical Indexing - Multiple Conditions
% I've talked about logical
% <http://blogs.mathworks.com/loren/category/indexing/ indexing> before in
% some of the linked posts, but recent work makes me want to show it off
% again.  One of the nice things about logical indexing is that it is very
% easy and natural to combine the results of different conditions to select
% items based on multiple criteria.
%% What is Logical Indexing?
% Suppose I have an array of integers, not sorted, and want to find the
% ones that are less than a certain number.  Here's how I can do it using
% the function <http://www.mathworks.com/help/matlab/ref/find.html |find|>.
X = randperm(20)
target = 5;
%%
ind = find(X < target)
%%
% You can see that find returns the indices into the array |X| that have
% values less than the |target|.  And we can use these to extract the
% values.
Xtarget = X(ind)
%%
% Another way to accomplish the same outcome is to use the logical
% expression to directly perform the indexing operation.  Here's what I
% mean.
logInd = X < target
%%
% MATLAB returns an array that matches the elements of the array |X|,
% element-by-element holding 1s where the matching values in |X| are the
% desired values, and 0s otherwise.  The array |logInd| is not an array of
% double numbers, but have the class |logical|.
whos logInd
%%
% I can now use this array to extract the desired values from |X|.
XtargetLogical = X(logInd)
%%
% Both methods return the results.
isequal(Xtarget, XtargetLogical)
%% Compound conditions.
% Let me create an anonymous function that returns true (|logical(1)|) for
% values that are even integers.
iseven = @(x) ~logical(rem(x,2))
%%
% Test |iseven|.
iseven(1:5)
%% Find Values Meeting More Than One Condition
% Now I would like to find the values in |X| that are less than |target|
% and are even. This is very natural to do with logical indexing.  We have
% the pieces of code we need already.
compoundCondInd = (X < target) &#038; iseven(X)
%%
% We can see we found suitable values at locations 3 and 19.  And we can
% extract those values next.
X(compoundCondInd)
%%  Did You Notice?
% Did you see how easy it is to combine multiple conditions?  I simply look
% for each of condition, getting back logical arrays, and then compute a
% logical array where the two input arrays are both true (via |&#038;|). I
% could, of course, calculate a compound condition where only either one or
% the other condition needs to be true using logical or (via |||).
%% A Recent Application
% I recently used this in the context of finding suspect data values.  I
% had 2 arrays, hourly temperature and speed.  The problem is that when the
% temperature gets near or below freezing, the speed sensor might freeze.
% But I didn't want to delete ALL the values below freezing.  So I looked
% for data where the temperature was sufficiently low AND the speed was
% very low (which could potentially mean the sensor was frozen).  That way,
% I did not need to discard all data at low temperatures.
%% Have You Used Compound Indexing?
% Did you do it like I did, using logical expressions?  Or did you use some
% other techniques?  What were you trying to achieve with your compound
% indexing?  Let me know <http://blogs.mathworks.com/loren/?p=637#respond
% here>.

##### SOURCE END ##### bc94e2aee9fb45b9b09b65745fcb27fb
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/LddjaaOsw6M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/02/20/logical-indexing-multiple-conditions/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/02/20/logical-indexing-multiple-conditions/</feedburner:origLink></item>
		<item>
		<title>Introduction to Functional Programming with Anonymous Functions, Part 3</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/mWWx3vydSzA/</link>
		<comments>http://blogs.mathworks.com/loren/2013/02/07/introduction-to-functional-programming-with-anonymous-functions-part-3/#comments</comments>
		<pubDate>Thu, 07 Feb 2013 12:18:56 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Function Handles]]></category>
		<category><![CDATA[functional programming]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=626</guid>
		<description><![CDATA[Tucker McClure is an Application Engineer with The MathWorks. He spends his time helping our customers accelerate their work with the right tools and problem-solving techniques. Today, he'll be discussing how "functional programming" can help create brief and powerful MATLAB code.ContentsRecapLoopsLoops via RecursionA Better LoopDoing More in a LoopFinal ExampleSummaryRecapFor Part 1, click here. For [...]]]></description>
				<content:encoded><![CDATA[<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<style type="text/css">

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

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

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

@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }

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

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

  </style><div class="content"><!--introduction--><p><a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/225094">Tucker McClure</a> is an Application Engineer with The MathWorks. He spends his time helping our customers accelerate their work with the right tools and problem-solving techniques. Today, he'll be discussing how "functional programming" can help create brief and powerful MATLAB code.</p><!--/introduction--><h3>Contents</h3><div><ul><li><a href="#fbd7e3ee-92ff-43b6-81f3-57ddc9c1bad8">Recap</a></li><li><a href="#d67c1251-5092-46c4-92d2-ec90d91b397a">Loops</a></li><li><a href="#15f6ff53-2e88-4c45-a182-587c356829ce">Loops via Recursion</a></li><li><a href="#17158a9d-0555-43db-8ec1-940e1db24e27">A Better Loop</a></li><li><a href="#cd7045ed-4b59-43a8-83ee-864e517f18d3">Doing More in a Loop</a></li><li><a href="#0ac5b619-0410-4f86-8707-136803bc052d">Final Example</a></li><li><a href="#557636cc-ac2e-4883-ac9d-ef26209d702e">Summary</a></li></ul></div><h4>Recap<a name="fbd7e3ee-92ff-43b6-81f3-57ddc9c1bad8"></a></h4><p>For Part 1, click <a href="http://blogs.mathworks.com/loren/?p=607">here</a>. For Part 2, click <a href="http://blogs.mathworks.com/loren/?p=611">here</a>.</p><p>When we left off, we had implemented conditional statements, recursion, and multi-line statements in anonymous functions, so today we'll tackle loops.</p><p>Before we get started, let's implement the functions that we'll need again.</p><pre class="codeinput">iif     = @(varargin) varargin{2*find([varargin{1:2:end}], 1, <span class="string">'first'</span>)}();
recur   = @(f, varargin) f(f, varargin{:});
curly   = @(x, varargin) x{varargin{:}};
</pre><h4>Loops<a name="d67c1251-5092-46c4-92d2-ec90d91b397a"></a></h4><p>Note that the recursive sequences we created in the last part could also have been implemented with <tt>for</tt> loops. For instance, here's factorial of <tt>n</tt>:</p><pre>   factorial = 1;
   for k = 1:n
       factorial = k * factorial;
   end</pre><p>Many times, recursive functions can be written iteratively in loops. However, we can't use <tt>for</tt> or <tt>while</tt> in an anonymous function, so instead of asking how we can unwrap recursive functions into iterative loops, let's ask the reverse: how can we implement loops with recursive functions?</p><h4>Loops via Recursion<a name="15f6ff53-2e88-4c45-a182-587c356829ce"></a></h4><p>To loop properly, one must know:</p><div><ul><li>What to do each iteration</li><li>If the process should continue to the next iteration</li><li>What's available when the loop begins</li></ul></div><p>Allowing the "what to do" to be a function (<tt>fcn</tt>) of some state (<tt>x</tt>), the "if it should continue" to be another function (<tt>cont</tt>) of the state, and "what's available when the loop begins" to be the initial state (<tt>x0</tt>), we can write a <tt>loop</tt> function. This is a big step, so bear with me for some explanation!</p><p>On each step, the loop function will call the <tt>cont</tt> function, passing in all elements of the state, <tt>x</tt>, as in <tt>cont(x{:})</tt>. If that returns false (meaning we shouldn't continue), the current state, <tt>x</tt>, is returned. Otherwise, if we <i>should</i> continue, it calls <tt>fcn</tt> with all elements of the current state, as in <tt>fcn(x{:})</tt>, and passes the output from that to the next iteration. Letting this single iteration be denoted as <tt>f</tt>, we can build the anonymous function <tt>loop</tt> using our <tt>recur</tt> function.</p><pre class="codeinput">loop = @(x0, cont, fcn) <span class="keyword">...</span><span class="comment">                                     % Header</span>
       recur(@(f, x) iif(~cont(x{:}), x, <span class="keyword">...</span><span class="comment">                    % Continue?</span>
                         true,        @() f(f, fcn(x{:}))), <span class="keyword">...</span><span class="comment"> %   Iterate</span>
             x0);                                               <span class="comment">% from x0.</span>
</pre><p>For this trivial example, the state is simply the iteration count. We'll increase the count every iteration until the count <tt>&gt;= n</tt> and return the final count. All this does therefore is count from 0 to the input <tt>n</tt>. Not very interesting, but it demonstrates the loop.</p><pre class="codeinput">count = @(n) loop({0}, <span class="keyword">...</span><span class="comment">          % Initialize state, k, to 0</span>
                  @(k) k &lt; n, <span class="keyword">...</span><span class="comment">   % While k &lt; n</span>
                  @(k) {k + 1});    <span class="comment">%   k = k + 1 (returned as cell array)</span>

arrayfun(count, 1:10)
</pre><pre class="codeoutput">ans = 
    [1]    [2]    [3]    [4]    [5]    [6]    [7]    [8]    [9]    [10]
</pre><p>I suppose that worked, but why are we using cell arrays to store the state, such as <tt>{0}</tt> and <tt>{k+1}</tt>? There are two reasons. First, if <tt>x</tt> is a cell array, then when we dump all elements of <tt>x</tt> into <tt>fcn</tt>, they become multiple arguments! That is, <tt>fcn(x{:})</tt> is the same as <tt>fcn(x{1}, x{2}, ...)</tt>. So instead of our function taking a big cell array for an input, it can take named arguments, which we'll use below. Second, we do this because it allows a function to <i>return</i> multiple elements that will be used by the next iteration, so if a function needed to return <tt>y</tt> and <tt>z</tt>, which would be arguments to the next iteration, it can simply return one cell array, <tt>{y, z}</tt>. It makes it easy to use. Here's a factorial example demonstrating this. The state is two different things: the iteration count, <tt>k</tt>, and factorial of the previous number, <tt>x</tt>. Note that both values of the state, <tt>k</tt> and <tt>x</tt>, are inputs to all of the functions. Note here how we're using <tt>@(k, x)</tt> for our functions. By allowing <tt>x</tt> to be a cell array, each element of the array becomes an argument such as <tt>k</tt> or <tt>x</tt>!</p><pre class="codeinput">factorial = @(n) loop({1, 1}, <span class="keyword">...</span><span class="comment">          % Start with k = 1 and x = 1</span>
                      @(k, x) k &lt;= n, <span class="keyword">...</span><span class="comment">  % While k &lt;= n</span>
                      @(k, x) {k + 1, <span class="keyword">...</span><span class="comment">  %   k = k + 1;</span>
                               k * x});    <span class="comment">%   x = k * x;</span>
</pre><p>Call it:</p><pre class="codeinput">factorial(5)
</pre><pre class="codeoutput">ans = 
    [6]    [120]
</pre><p>Wait, we wanted 120 (the fifth number of the factorial sequence), so what's that 6 doing there?</p><h4>A Better Loop<a name="17158a9d-0555-43db-8ec1-940e1db24e27"></a></h4><p>Remember how we return the full state? That's not very useful for this factorial example, as we get both <tt>k</tt> and the number we want as outputs in that cell array. Because the whole state isn't generally useful, let's add a <tt>cleanup</tt> function to our loop. We'll execute this when the loop is done (right after <tt>~cont(...)</tt> returns <tt>false</tt>). Our <tt>cleanup</tt> function will take the full state and return only the important parts.</p><pre class="codeinput">loop = @(x0, cont, fcn, cleanup) <span class="keyword">...</span><span class="comment">                            % Header</span>
       recur(@(f, x) iif(~cont(x{:}), cleanup(x{:}), <span class="keyword">...</span><span class="comment">        % Continue?</span>
                         true,        @() f(f, fcn(x{:}))), <span class="keyword">...</span><span class="comment"> %   Iterate</span>
             x0);                                               <span class="comment">% from x0.</span>
</pre><p>Now here's factorial, with clean output.</p><pre class="codeinput">factorial = @(n) loop({1, 1}, <span class="keyword">...</span><span class="comment">         % Start with k = 1 and x = 1</span>
                      @(k,x) k &lt;= n, <span class="keyword">...</span><span class="comment">  % While k &lt;= n</span>
                      @(k,x) {k + 1, <span class="keyword">...</span><span class="comment">  %   k = k + 1;</span>
                              k * x}, <span class="keyword">...</span><span class="comment"> %   x = k * x;</span>
                      @(k,x) x);          <span class="comment">% End, returning x</span>
</pre><p>The result:</p><pre class="codeinput">factorial(5)
</pre><pre class="codeoutput">ans =
   120
</pre><p>First seven numbers of factorial:</p><pre class="codeinput">arrayfun(factorial, 1:7)
</pre><pre class="codeoutput">ans =
  Columns 1 through 6
           1           2           6          24         120         720
  Column 7
        5040
</pre><p>That's better.</p><p>I'll be the first to admit that the loop is a bit longer and much more rigid than a normal MATLAB loop. On the other hand, it can be used in anonymous functions, and its syntax has a certain cleanliness to it in that it doesn't modify any variables that live outside the loop; it has its own scope. This is one nice feature of <tt>loop</tt> being a <i>function</i> that takes <i>code</i> (functions) as arguments.</p><h4>Doing More in a Loop<a name="cd7045ed-4b59-43a8-83ee-864e517f18d3"></a></h4><p>Let's say we want to do something else in the loop, but don't want its output passed to the next iteration, like printing something out. Remember the <tt>do_three_things</tt> example from last time? We executed numerous statements by putting them in a cell array and used <tt>curly</tt> to access the output we cared about. We can do that here, in a loop. For example, let's write out a function to print <tt>n</tt> digits of the factorial sequence. We'll use an array to store two things. The first will be the number that <tt>fprintf</tt> returns, which we don't care about. The second will be the cell array we want to return, <tt>k</tt> and <tt>x</tt>. We'll access that cell array with <tt>curly</tt>, as in <tt>curly({..., {k, x}}, 2)</tt>, which just returns <tt>{k, x}</tt>.</p><pre class="codeinput">say_it = @(k, x) fprintf(<span class="string">'Factorial(%d): %d\n'</span>, k, x);
print_factorial = @(n) loop({1, 1}, <span class="keyword">...</span><span class="comment">               % Start with k=1, x=1</span>
                      @(k,x) k &lt;= n, <span class="keyword">...</span><span class="comment">              % While k &lt;= n</span>
                      @(k,x) curly({say_it(k,k*x),<span class="keyword">...</span><span class="comment"> % Print, discard</span>
                                    {k + 1, <span class="keyword">...</span><span class="comment">       %   k = k + 1;</span>
                                     k * x}}, <span class="keyword">...</span><span class="comment">     %   x = k * x;</span>
                                   2), <span class="keyword">...</span><span class="comment">            %   Return {k+1,k*x}.</span>
                      @(k,x) x);                      <span class="comment">% End, returning x</span>
</pre><pre class="codeinput">print_factorial(7);
</pre><pre class="codeoutput">Factorial(1): 1
Factorial(2): 2
Factorial(3): 6
Factorial(4): 24
Factorial(5): 120
Factorial(6): 720
Factorial(7): 5040
</pre><p>Now we're executing multiple things and only returning what we want while inside a loop built built on recursion and anonymous conditionals! We've come a long way since Part 1.</p><p>As a practical note, recall that because these loops use recursion, there's a limit to the number of times they can loop (MATLAB has a recursion limit, which is a setting in Preferences). Also, a recursive implementation of a loop isn't the most efficient. For this reason, it's best to implement <tt>loop</tt> itself in a file that can then be used in the same way. If it's in a file, it can also be kept on the MATLAB path so that it can be used anywhere.</p><pre>   function x = loop(x, cont, f, cleanup)
       while cont(x{:})
           x = f(x{:});
       end
       if nargin == 4
           x = cleanup(x{:});
       end
   end</pre><h4>Final Example<a name="0ac5b619-0410-4f86-8707-136803bc052d"></a></h4><p>This brings us to our final example. Below, we'll simulate a simple <a href="http://en.wikipedia.org/wiki/Harmonic_oscillator">harmonic oscillator</a> over time, using a structure to store dissimilar states, including a complete time history of the oscillator. This might simulate, for example, the sway of a lamp that's hanging from the ceiling after an earthquake.</p><pre class="codeinput"><span class="comment">% First, calculate a state transition matrix that represents a harmonic</span>
<span class="comment">% oscillator with damping. Multiplying this by |x| produces |x| at a</span>
<span class="comment">% slightly later time. The math here isn't important to the example.</span>
Phi = expm(0.5*[0 1; -1 -0.2]);

<span class="comment">% Now create the loop.</span>
x   = loop({[1; 0], 1}, <span class="keyword">...</span><span class="comment">                  % Initial state, x = [1; 0]</span>
           @(x,k) k &lt;= 100, <span class="keyword">...</span><span class="comment">              % While k &lt;= 100</span>
           @(x,k) {[x, Phi * x(:, end)], <span class="keyword">...</span><span class="comment"> %   Update x</span>
                   k + 1}, <span class="keyword">...</span><span class="comment">               %   Update k</span>
           @(x,k) x);                        <span class="comment">% End, return x</span>

<span class="comment">% Create a plot function.</span>
plot_it = @(n, x, y, t) {subplot(2, 1, n), <span class="keyword">...</span><span class="comment">            % Select subplot.</span>
                         plot(x(n, :)), <span class="keyword">...</span><span class="comment">               % Plot the data.</span>
                         iif(nargin==4, @() title(t), <span class="keyword">...</span><span class="comment"> % If there's a</span>
                             true,      []), <span class="keyword">...</span><span class="comment">          % title, add it.</span>
                         ylabel(y), <span class="keyword">...</span><span class="comment">                   % Label y</span>
                         xlabel(<span class="string">'Time (s)'</span>)};             <span class="comment">% and x axes.</span>

<span class="comment">% Plot the result.</span>
plot_it(1, x, <span class="string">'Position (m)'</span>, <span class="string">'Harmonic Oscillator'</span>);
plot_it(2, x, <span class="string">'Velocity (m/s)'</span>);
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/functional_programming_techniques_3_01.png" alt=""> <h4>Summary<a name="557636cc-ac2e-4883-ac9d-ef26209d702e"></a></h4><p>That's it for loops via recursion!</p><p>Let's look back at what we did over these three parts. First, we started with a simple <tt>map</tt> utility function to demonstrate the function-of-functions idea. Then we created our ubiquitous inline if, which further enabled recursion (a conditional is necessary to make recursion stop!). We also showed using multiple statements by storing their outputs in a cell array. Finally, we created a <tt>loop</tt> construct on top of our recursion functions.</p><p>At this point, we've done more than just scratch the surface of functional programming. We've used MATLAB's interesting constructs, such as function handles, cell arrays, and <tt>varargin</tt> to implement a functional programming framework, allowing a new syntax within MATLAB, where code can be arguments to flow control functions. Here's a roundup of what we created.</p><pre class="codeinput">map   = @(val, fcns) cellfun(@(f) f(val{:}), fcns);
mapc  = @(val, fcns) cellfun(@(f) f(val{:}), fcns, <span class="string">'UniformOutput'</span>, 0);
iif   = @(varargin) varargin{2*find([varargin{1:2:end}], 1, <span class="string">'first'</span>)}();
recur = @(f, varargin) f(f, varargin{:});
paren = @(x, varargin) x(varargin{:});
curly = @(x, varargin) x{varargin{:}};
loop  = @(x0,c,f,r)recur(@(g,x)iif(c(x{:}),@()g(g,f(x{:})),1,r(x{:})),x0);
</pre><p>These have also been programmed as "normal" MATLAB functions so that they can be kept on the path and used whenever they're needed. These can be found under "Functional Programming Constructs" in File Exchange, <a href="http://www.mathworks.com/matlabcentral/fileexchange/39735-functional-programming-constructs">here</a>.</p><p>Thanks for reading. I hope this has both enabled a new level of detail in anonymous functions in MATLAB and helped demonstrate the wide range of possibilities available within the MATLAB language.</p><p>Do you have other functional programming patterns you use in your code? For instance, a do-while loop is just like our loop above except that it always runs at least one iteration. Any ideas how to program this or other interesting constructs in anonymous functions? Please let us know <a href="http://blogs.mathworks.com/loren/?p=626#respond">here</a>!</p><script language="JavaScript"> <!-- 
    function grabCode_fee28ac6c0854f4d8c4456a6d8df6e0c() {
        // 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='fee28ac6c0854f4d8c4456a6d8df6e0c ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' fee28ac6c0854f4d8c4456a6d8df6e0c';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_fee28ac6c0854f4d8c4456a6d8df6e0c()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><!--
fee28ac6c0854f4d8c4456a6d8df6e0c ##### SOURCE BEGIN #####
%% Introduction to Functional Programming with Anonymous Functions, Part 3
%
% <http://www.mathworks.com/matlabcentral/fileexchange/authors/225094 
% Tucker McClure> is an Application Engineer with The MathWorks. He spends
% his time helping our customers accelerate their work with the right tools
% and problem-solving techniques. Today, he'll be discussing how
% "functional programming" can help create brief and powerful MATLAB code.

%% Recap
% For Part 1, click <http://blogs.mathworks.com/loren/?p=607 here>.
% For Part 2, click <http://blogs.mathworks.com/loren/?p=611 here>.
%
% When we left off, we had implemented conditional statements, recursion,
% and multi-line statements in anonymous functions, so today we'll tackle 
% loops.
% 
% Before we get started, let's implement the functions that we'll need 
% again.

iif     = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();
recur   = @(f, varargin) f(f, varargin{:});
curly   = @(x, varargin) x{varargin{:}};

%% Loops
%
% Note that the recursive sequences we created in the last part could also
% have been implemented with |for| loops. For instance, here's factorial 
% of |n|:
% 
%     factorial = 1;
%     for k = 1:n
%         factorial = k * factorial;
%     end
% 
% Many times, recursive functions can be written iteratively in loops.
% However, we can't use |for| or |while| in an anonymous function, so 
% instead of asking how we can unwrap recursive functions into iterative 
% loops, let's ask the reverse: how can we implement loops with recursive 
% functions?

%% Loops via Recursion
%
% To loop properly, one must know:
% 
% * What to do each iteration
% * If the process should continue to the next iteration
% * What's available when the loop begins
% 
% Allowing the "what to do" to be a function (|fcn|) of some state (|x|),
% the "if it should continue" to be another function (|cont|) of the state,
% and "what's available when the loop begins" to be the initial state 
% (|x0|), we can write a |loop| function. This is a big step, so bear with
% me for some explanation!
%
% On each step, the loop function will call the |cont| function, passing in
% all elements of the state, |x|, as in |cont(x{:})|. If that returns false
% (meaning we shouldn't continue), the current state, |x|, is returned.
% Otherwise, if we _should_ continue, it calls |fcn| with all elements of 
% the current state, as in |fcn(x{:})|, and passes the output from that to
% the next iteration. Letting this single iteration be denoted as |f|, we
% can build the anonymous function |loop| using our |recur| function.

loop = @(x0, cont, fcn) ...                                     % Header
       recur(@(f, x) iif(~cont(x{:}), x, ...                    % Continue?
                         true,        @() f(f, fcn(x{:}))), ... %   Iterate
             x0);                                               % from x0.

%%
% For this trivial example, the state is simply the iteration count. We'll
% increase the count every iteration until the count |>= n| and return the
% final count. All this does therefore is count from 0 to the input |n|.
% Not very interesting, but it demonstrates the loop.

count = @(n) loop({0}, ...          % Initialize state, k, to 0
                  @(k) k < n, ...   % While k < n
                  @(k) {k + 1});    %   k = k + 1 (returned as cell array)

arrayfun(count, 1:10)

%%
% I suppose that worked, but why are we using cell arrays to store the 
% state, such as |{0}| and |{k+1}|? There are two reasons. First, if |x| is
% a cell array, then when we dump all elements of |x| into |fcn|, they 
% become multiple arguments! That is, |fcn(x{:})| is the same as 
% |fcn(x{1}, x{2}, ...)|. So instead of our function taking a big cell array for an input, it can take named 
% arguments, which we'll use below. Second, we do this because it allows a function to _return_ 
% multiple elements that will be used by the next iteration, so if a 
% function needed to return |y| and |z|, which would be arguments to the 
% next iteration, it can simply return one cell array, |{y, z}|. It makes 
% it easy to use. Here's a factorial example demonstrating this. The state 
% is two different things: the iteration count, |k|, and factorial of the 
% previous number, |x|. Note that both values of the state, |k| and |x|, 
% are inputs to all of the functions. Note here how we're using |@(k, x)|
% for our functions. By allowing |x| to be a cell array, each element of
% the array becomes an argument such as |k| or |x|!

factorial = @(n) loop({1, 1}, ...          % Start with k = 1 and x = 1
                      @(k, x) k <= n, ...  % While k <= n
                      @(k, x) {k + 1, ...  %   k = k + 1;
                               k * x});    %   x = k * x;

%%
% Call it:

factorial(5)

%%
% Wait, we wanted 120 (the fifth number of the factorial sequence), so
% what's that 6 doing there?

%% A Better Loop
% Remember how we return the full state? That's not very useful for this
% factorial example, as we get both |k| and the number we want as outputs
% in that cell array. Because the whole state isn't generally useful, let's
% add a |cleanup| function to our loop. We'll execute this when the loop is
% done (right after |~cont(...)| returns |false|). Our |cleanup| function
% will take the full state and return only the important parts.

loop = @(x0, cont, fcn, cleanup) ...                            % Header
       recur(@(f, x) iif(~cont(x{:}), cleanup(x{:}), ...        % Continue?
                         true,        @() f(f, fcn(x{:}))), ... %   Iterate
             x0);                                               % from x0.

%%
% Now here's factorial, with clean output.

factorial = @(n) loop({1, 1}, ...         % Start with k = 1 and x = 1
                      @(k,x) k <= n, ...  % While k <= n
                      @(k,x) {k + 1, ...  %   k = k + 1;
                              k * x}, ... %   x = k * x;
                      @(k,x) x);          % End, returning x

%%
% The result:
factorial(5)

%%
% First seven numbers of factorial:

arrayfun(factorial, 1:7)

%%
% That's better.
%
% I'll be the first to admit that the loop is a bit longer and much more 
% rigid than a normal MATLAB loop. On the other hand, it can be used in
% anonymous functions, and its syntax has a certain cleanliness to it in
% that it doesn't modify any variables that live outside the loop; it has
% its own scope. This is one nice feature of |loop| being a _function_ that
% takes _code_ (functions) as arguments.

%% Doing More in a Loop
% Let's say we want to do something else in the loop, but don't want its
% output passed to the next iteration, like printing something out.
% Remember the |do_three_things| example from last time? We executed
% numerous statements by putting them in a cell array and used |curly| to
% access the output we cared about. We can do that here, in a loop. For
% example, let's write out a function to print |n| digits of the factorial
% sequence. We'll use an array to store two things. The first will be the
% number that |fprintf| returns, which we don't care about. The second will
% be the cell array we want to return, |k| and |x|. We'll access that cell
% array with |curly|, as in |curly({..., {k, x}}, 2)|, which just
% returns |{k, x}|.

say_it = @(k, x) fprintf('Factorial(%d): %d\n', k, x);
print_factorial = @(n) loop({1, 1}, ...               % Start with k=1, x=1
                      @(k,x) k <= n, ...              % While k <= n
                      @(k,x) curly({say_it(k,k*x),... % Print, discard
                                    {k + 1, ...       %   k = k + 1;
                                     k * x}}, ...     %   x = k * x;
                                   2), ...            %   Return {k+1,k*x}.
                      @(k,x) x);                      % End, returning x

%%
print_factorial(7);

%%
% Now we're executing multiple things and only returning what we want while
% inside a loop built built on recursion and anonymous conditionals! We've
% come a long way since Part 1.

%%
% As a practical note, recall that because these loops use recursion,
% there's a limit to the number of times they can loop (MATLAB has a
% recursion limit, which is a setting in Preferences). Also, a recursive
% implementation of a loop isn't the most efficient. For this reason, it's
% best to implement |loop| itself in a file that can then be used in the
% same way. If it's in a file, it can also be kept on the MATLAB path so 
% that it can be used anywhere.
% 
%     function x = loop(x, cont, f, cleanup)
%         while cont(x{:})
%             x = f(x{:});
%         end
%         if nargin == 4
%             x = cleanup(x{:});
%         end
%     end
         
%% Final Example
% This brings us to our final example. Below, we'll simulate a simple
% <http://en.wikipedia.org/wiki/Harmonic_oscillator harmonic oscillator>
% over time, using a structure to store dissimilar states, including a 
% complete time history of the oscillator. This might simulate, for 
% example, the sway of a lamp that's hanging from the ceiling after an 
% earthquake.

% First, calculate a state transition matrix that represents a harmonic
% oscillator with damping. Multiplying this by |x| produces |x| at a 
% slightly later time. The math here isn't important to the example.
Phi = expm(0.5*[0 1; -1 -0.2]);

% Now create the loop.
x   = loop({[1; 0], 1}, ...                  % Initial state, x = [1; 0]
           @(x,k) k <= 100, ...              % While k <= 100
           @(x,k) {[x, Phi * x(:, end)], ... %   Update x
                   k + 1}, ...               %   Update k
           @(x,k) x);                        % End, return x

% Create a plot function.
plot_it = @(n, x, y, t) {subplot(2, 1, n), ...            % Select subplot.
                         plot(x(n, :)), ...               % Plot the data.
                         iif(nargin==4, @() title(t), ... % If there's a
                             true,      []), ...          % title, add it.
                         ylabel(y), ...                   % Label y
                         xlabel('Time (s)')};             % and x axes.

% Plot the result.
plot_it(1, x, 'Position (m)', 'Harmonic Oscillator');
plot_it(2, x, 'Velocity (m/s)');

%% Summary
% That's it for loops via recursion! 
%
% Let's look back at what we did over these three parts. First, we started
% with a simple |map| utility function to demonstrate the
% function-of-functions idea. Then we created our ubiquitous inline if,
% which further enabled recursion (a conditional is necessary to make
% recursion stop!). We also showed using multiple statements by storing
% their outputs in a cell array. Finally, we created a |loop| construct on 
% top of our recursion functions.
% 
% At this point, we've done more than just scratch the surface of 
% functional programming. We've used MATLAB's interesting constructs, such 
% as function handles, cell arrays, and |varargin| to implement a 
% functional programming framework, allowing a new syntax within MATLAB,
% where code can be arguments to flow control functions. Here's a roundup
% of what we created.

map   = @(val, fcns) cellfun(@(f) f(val{:}), fcns);
mapc  = @(val, fcns) cellfun(@(f) f(val{:}), fcns, 'UniformOutput', 0);
iif   = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();
recur = @(f, varargin) f(f, varargin{:});
paren = @(x, varargin) x(varargin{:});
curly = @(x, varargin) x{varargin{:}};
loop  = @(x0,c,f,r)recur(@(g,x)iif(c(x{:}),@()g(g,f(x{:})),1,r(x{:})),x0);

%%
% These have also been programmed as "normal" MATLAB functions so that they
% can be kept on the path and used whenever they're needed. These can be
% found under "Functional Programming Constructs" in File Exchange, 
% <http://www.mathworks.com/matlabcentral/fileexchange/39735-functional-programming-constructs
% here>.
%
% Thanks for reading. I hope this has both enabled a new level of detail in
% anonymous functions in MATLAB and helped demonstrate the wide range of
% possibilities available within the MATLAB language.
%
% Do you have other functional programming patterns you use in your code? 
% For instance, a do-while loop is just like our loop above except that it
% always runs at least one iteration. Any ideas how to program this or 
% other interesting constructs in anonymous functions? Please let us know 
% <http://blogs.mathworks.com/loren/?p=626#respond here>!

##### SOURCE END ##### fee28ac6c0854f4d8c4456a6d8df6e0c
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/mWWx3vydSzA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/02/07/introduction-to-functional-programming-with-anonymous-functions-part-3/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/02/07/introduction-to-functional-programming-with-anonymous-functions-part-3/</feedburner:origLink></item>
		<item>
		<title>Introduction to Functional Programming with Anonymous Functions, Part 2</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/pbQ7kUuN8gg/</link>
		<comments>http://blogs.mathworks.com/loren/2013/01/24/introduction-to-functional-programming-with-anonymous-functions-part-2/#comments</comments>
		<pubDate>Thu, 24 Jan 2013 16:00:13 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Function Handles]]></category>
		<category><![CDATA[functional programming]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=611</guid>
		<description><![CDATA[Tucker McClure is an Application Engineer with The MathWorks. He spends his time helping our customers accelerate their work with the right tools and problem-solving techniques. Today, he'll be discussing how "functional programming" can help create brief and powerful MATLAB code.ContentsRecapAnonymous Function RecursionHelpersExecuting Multiple StatementsTo Be ContinuedRecapFor Part 1, click here.Last time, we said that [...]]]></description>
				<content:encoded><![CDATA[<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<style type="text/css">

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

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

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

@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }

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

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

  </style><div class="content"><!--introduction--><p><a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/225094">Tucker McClure</a> is an Application Engineer with The MathWorks. He spends his time helping our customers accelerate their work with the right tools and problem-solving techniques. Today, he'll be discussing how "functional programming" can help create brief and powerful MATLAB code.</p><!--/introduction--><h3>Contents</h3><div><ul><li><a href="#1768cbcf-cd3a-4edf-a484-4b2c26f6fa39">Recap</a></li><li><a href="#b0cc1edc-05b5-4668-a8ea-3752f7f74804">Anonymous Function Recursion</a></li><li><a href="#db344cb8-ae1b-4b25-8071-af3883a49003">Helpers</a></li><li><a href="#eadbce51-e1cc-46e9-80ea-58f1108621fc">Executing Multiple Statements</a></li><li><a href="#08367508-8f1c-490e-83ed-ab6204d28e95">To Be Continued</a></li></ul></div><h4>Recap<a name="1768cbcf-cd3a-4edf-a484-4b2c26f6fa39"></a></h4><p>For Part 1, click <a href="http://blogs.mathworks.com/loren/2013/01/10/introduction-to-functional-prog">here</a>.</p><p>Last time, we said that functional programming was marked by storing functions as variables (function handles) and working with functions that act on other functions. We put these ideas together to implement our own version of a <tt>map</tt> function for handling multiple inputs and outputs from multiple functions simultaneously, and we created <tt>iif</tt>, an "inline if", to allow the use of conditional statements inside of anonymous functions. So how might we work with recursive functions -- functions of themselves? We'll see how a functional programming style allows us to implement recursive functionality inside anonymous functions, and this will pave the way for the final part, in which we'll implement loops, without ever using <tt>for</tt> or <tt>while</tt> (which we can't use in anonymous functions).</p><p>Before we get started, let's implement <tt>iif</tt> again; we're going to need it frequently.</p><pre class="codeinput">iif = @(varargin) varargin{2*find([varargin{1:2:end}], 1, <span class="string">'first'</span>)}();
</pre><h4>Anonymous Function Recursion<a name="b0cc1edc-05b5-4668-a8ea-3752f7f74804"></a></h4><p>Recall that a recursive function is a function that calls itself. It therefore needs some way to refer to itself. When we write an anonymous function, it isn't "named" (hence, "anonymous"), so it can't call itself by name. How can we get around this?</p><p>Let's start with a Fibonacci sequence example. Recall that the nth number of the Fibonacci sequence is the sum of the previous two numbers, starting with 1 and 1, yielding 1, 1, 2, 3, 5, 8, 13, 21, etc. This is easy to implement recursively.</p><pre>   fib = @(n) iif(n &lt;= 2, 1, ...                    % First two numbers
                  true,   @() fib(n-1) + fib(n-2)); % All later numbers</pre><p>But hey, that can't work! We haven't defined <tt>fib</tt> yet, so how could this anonymous function call it? In fact, the anonymous function will never "know" we're referring to it as <tt>fib</tt>, so this won't work at all. Therefore, instead of trying to call <tt>fib</tt> directly, let's provide another input: the handle of a function to call, <tt>f</tt>.</p><pre class="codeinput">fib = @(f, n) iif(n &lt;= 2, 1, <span class="keyword">...</span><span class="comment">                      % First two numbers</span>
                  true,   @() f(f, n-1) + f(f, n-2)); <span class="comment">% All later numbers</span>
</pre><p>Getting closer. Now, if we pass <tt>fib</tt> <i>to</i> <tt>fib</tt> along with the number we want, it will call <tt>fib</tt>, passing in <tt>fib</tt> as the first argument, recursively until we get our answer.</p><pre class="codeinput">fib(fib, 6)
</pre><pre class="codeoutput">ans =
     8
</pre><p>Ok, that's right. The sixth number of the sequence is 8. On the other hand, the syntax we've created is terrible. We have to provide the function to itself? I'd rather not. Instead, let's just write a new function that hands <tt>fib</tt> to <tt>fib</tt> along with the input <tt>n</tt>.</p><pre class="codeinput">fib2 = @(n) fib(fib, n);

fib2(4)
fib2(5)
fib2(6)
</pre><pre class="codeoutput">ans =
     3
ans =
     5
ans =
     8
</pre><p>That's a lot closer to what we want, but there's one more step. Let's write a function called <tt>recur</tt> to hand a function handle to itself, along with any other arguments. This makes recursion less cumbersome.</p><pre class="codeinput">recur = @(f, varargin) f(f, varargin{:});
</pre><p>That was simple, so now let's re-write <tt>fib</tt>. The first argument to <tt>recur</tt> is the function, which we'll define inline. The second is <tt>n</tt>. That's all there is to it. It now reads as "Recursively call a function that, if <tt>k &lt;= 2</tt>, returns one, and otherwise returns the recursive function of <tt>k-1</tt> plus that of <tt>k-2</tt>, starting with the user's input <tt>n</tt>." (If it doesn't read quite this clearly at first, that's ok. It takes some getting used to. Comment liberally if necessary!)</p><pre class="codeinput">fib = @(n) recur(@(f, k) iif(k &lt;= 2, 1, <span class="keyword">...</span>
                             true,   @() f(f, k-1) + f(f, k-2)), <span class="keyword">...</span>
                 n);
</pre><p>And we can find the first ten numbers of the sequence via <a href="http://www.mathworks.com/help/matlab/ref/arrayfun.html">arrayfun</a>.</p><pre class="codeinput">arrayfun(fib, 1:10)
</pre><pre class="codeoutput">ans =
     1     1     2     3     5     8    13    21    34    55
</pre><p>Factorial (f(n) = 1 * 2 * 3 * ... n) is another easy operation to represent recursively.</p><pre class="codeinput">factorial = @(n) recur(@(f, k) iif(k == 0, 1, <span class="keyword">...</span>
                                   true,   @() k * f(f, k-1)), n);
arrayfun(factorial, 1:7)
</pre><pre class="codeoutput">ans =
  Columns 1 through 6
           1           2           6          24         120         720
  Column 7
        5040
</pre><p>A number to an integer power has a nearly identical form. Here's <tt>4.^(0:5)</tt>.</p><pre class="codeinput">pow = @(x, n) recur(@(f, k) iif(k == 0, 1, <span class="keyword">...</span>
                                true,   @() x * f(f, k-1)), n);
arrayfun(@(n) pow(4, n), 0:5)
</pre><pre class="codeoutput">ans =
           1           4          16          64         256        1024
</pre><p>That was a big step for anonymous functions, using both recursion and an inline conditional together with ease. Like <tt>map</tt> and <tt>iif</tt>, <tt>recur</tt>, looks strange at first, but once it's been seen, it's hard to forget how it works (just make one of the inputs a function handle and pass it to itself). And recursion doesn't have to stop at interesting mathematical sequences of numbers. For instance, in the next part, we'll use this to implement loops in, but first, we'll need a some helper functions and a good way to execute multiple statements in an anonymous function.</p><h4>Helpers<a name="db344cb8-ae1b-4b25-8071-af3883a49003"></a></h4><p>These little functions are useful in many circumstances, and we're going to need <tt>curly</tt> frequently.</p><pre class="codeinput">paren = @(x, varargin) x(varargin{:});
curly = @(x, varargin) x{varargin{:}};
</pre><p>They allow us to write <tt>x(3, 4)</tt> as <tt>paren(x, 3, 4)</tt> and similarly for curly braces. That is, now we can think of parentheses and curly braces as functions! At first this might not seem useful. However, imagine writing a function to return the width and height of the screen. The data we need is available from this call:</p><pre class="codeinput">get(0, <span class="string">'ScreenSize'</span>)
</pre><pre class="codeoutput">ans =
           1           1        1920        1200
</pre><p>However, we don't need those preceeding ones. We could save the output to a variable, say <tt>x</tt>, and then access x(3:4), but if we need this in an anonymous function, we can't save to a variable. How do we access just elements 3 and 4? There are numerous ways, but <tt>paren</tt> and <tt>curly</tt> are similar to constructs found in other languages and are easy to use, so we'll use those here.</p><p>Now we can write our <tt>screen_size</tt> function to return just the data we want.</p><pre class="codeinput">screen_size = @() paren(get(0, <span class="string">'ScreenSize'</span>), 3:4);

screen_size()
</pre><pre class="codeoutput">ans =
        1920        1200
</pre><p>While on the subject, note that we can actually use any number of indices or even ':'.</p><pre class="codeinput">magic(3)
paren(magic(3), 1:2, 2:3)
paren(magic(3), 1:2, :)
</pre><pre class="codeoutput">ans =
     8     1     6
     3     5     7
     4     9     2
ans =
     1     6
     5     7
ans =
     8     1     6
     3     5     7
</pre><p>We do the same with the curly braces. Here, the regular expression pattern will match both 'rain' and 'Spain', but we'll only select the second match.</p><pre class="codeinput">spain = curly(regexp(<span class="string">'The rain in Spain....'</span>, <span class="string">'\s(\S+ain)'</span>, <span class="string">'tokens'</span>), 2)
</pre><pre class="codeoutput">spain = 
    'Spain'
</pre><p>(Click for <a href="http://www.mathworks.com/help/matlab/ref/regexp.html">Regexp help</a>.)</p><p>It also works with ':' (note that the single quotes are required).</p><pre class="codeinput">[a, b] = curly({<span class="string">'the_letter_a'</span>, <span class="string">'the_letter_b'</span>}, <span class="string">':'</span>)
</pre><pre class="codeoutput">a =
the_letter_a
b =
the_letter_b
</pre><h4>Executing Multiple Statements<a name="eadbce51-e1cc-46e9-80ea-58f1108621fc"></a></h4><p>With <tt>curly</tt> in place, let's examine something a little different. Consider the following:</p><pre class="codeinput">do_three_things = @() {fprintf(<span class="string">'This is the first thing.\n'</span>), <span class="keyword">...</span>
                       fprintf(<span class="string">'This is the second thing.\n'</span>), <span class="keyword">...</span>
                       max(eig(magic(3)))};

do_three_things()
</pre><pre class="codeoutput">This is the first thing.
This is the second thing.
ans = 
    [25]    [26]    [15]
</pre><p>We've executed three statements on a single line. All of the outputs are stored in the cell array, so we have three elements in the cell array. The first two outputs are actually garbage as far as we're concerned (they're just the outputs from <tt>fprintf</tt>, which is the number of bytes written, which we don't care about at all). The last output is from <tt>max(eig(magic(3)))</tt>; That is, the biggest eigenvalue of <tt>magic(3)</tt> is exactly 15. Let's say we just wanted that final value, the eigenvalue. It's the third element of the cell array, so we can grab it with <tt>curly</tt>.</p><pre class="codeinput">do_three_things = @() curly({fprintf(<span class="string">'This is the first thing.\n'</span>), <span class="keyword">...</span>
                             fprintf(<span class="string">'This is the second thing.\n'</span>), <span class="keyword">...</span>
                             max(eig(magic(3)))}, 3);

do_three_things()
</pre><pre class="codeoutput">This is the first thing.
This is the second thing.
ans =
           15
</pre><p>For a more complex example, let's say we want to write a function to:</p><div><ol><li>Create a small figure in the middle of the screen</li><li>Plot some random points</li><li>Return the handles of the figure and the plot</li></ol></div><p>Then by storing all of the outputs in a cell array and using <tt>curly</tt> to access the outputs we care about, we can make a multi-line function with multiple outputs, all in a simple anonymous function.</p><pre class="codeinput">dots = @() curly({<span class="keyword">...</span>
    figure(<span class="string">'Position'</span>, [0.5*screen_size() - [100 50], 200, 100], <span class="keyword">...</span>
           <span class="string">'MenuBar'</span>,  <span class="string">'none'</span>), <span class="keyword">...</span><span class="comment">                % Position the figure</span>
    plot(randn(1, 100), randn(1, 100), <span class="string">'.'</span>)}, <span class="keyword">...</span><span class="comment">  % Plot random points</span>
    <span class="string">':'</span>);                                          <span class="comment">% Return everything</span>

[h_figure, h_dots] = dots()
</pre><pre class="codeoutput">h_figure =
     3
h_dots =
          187
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/2013/functional_programming_techniques_2_01.png" alt=""> <p>(As a quick aside, note that if a statement doesn't return anything, we can't put it in a cell array, and so we can't use it this way. There are ways around this, discussed <a href="http://www.mathworks.com/matlabcentral/fileexchange/39735-functional-programming-constructs">here</a>.)</p><h4>To Be Continued<a name="08367508-8f1c-490e-83ed-ab6204d28e95"></a></h4><p>Today, we've come a long way, from a simple condition through recursion and executing multiple statements. Here's a roundup of the functions so far.</p><pre class="codeinput">map     = @(val, fcns) cellfun(@(f) f(val{:}), fcns);
mapc    = @(val, fcns) cellfun(@(f) f(val{:}), fcns, <span class="string">'UniformOutput'</span>, 0);
iif     = @(varargin) varargin{2*find([varargin{1:2:end}], 1, <span class="string">'first'</span>)}();
recur   = @(f, varargin) f(f, varargin{:});
paren   = @(x, varargin) x(varargin{:});
curly   = @(x, varargin) x{varargin{:}};
</pre><p>These can also be found <a href="http://www.mathworks.com/matlabcentral/fileexchange/39735-functional-programming-constructs">here</a>, implemented as regular MATLAB functions that can be kept on the path.</p><p>Next time, we'll look at loops. Until then, have you worked with functions such as <tt>paren</tt> or <tt>curly</tt>? How else are people implementing these or similar operations? Let us know <a href="http://blogs.mathworks.com/loren/?p=611#respond">here</a>.</p><script language="JavaScript"> <!-- 
    function grabCode_785282659a42421c916b8b165e146cdb() {
        // 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='785282659a42421c916b8b165e146cdb ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 785282659a42421c916b8b165e146cdb';
    
        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;');

        copyright = 'Copyright 2013 The MathWorks, Inc.';

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

        // Add copyright line at the bottom if specified.
        if (copyright.length > 0) {
            d.writeln('');
            d.writeln('%%');
            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_785282659a42421c916b8b165e146cdb()"><span style="font-size: x-small;        font-style: italic;">Get 
      the MATLAB code <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; R2012b<br /></p><p class="footer"><br />
      Published with MATLAB&reg; R2012b<br /></p></div><!--
785282659a42421c916b8b165e146cdb ##### SOURCE BEGIN #####
%% Introduction to Functional Programming with Anonymous Functions, Part 2
%
% <http://www.mathworks.com/matlabcentral/fileexchange/authors/225094 
% Tucker McClure> is an Application Engineer with The MathWorks. He spends
% his time helping our customers accelerate their work with the right tools
% and problem-solving techniques. Today, he'll be discussing how
% "functional programming" can help create brief and powerful MATLAB code.

%% Recap
% For Part 1, click
% <http://blogs.mathworks.com/loren/2013/01/10/introduction-to-functional-prog
% here>.
%
% Last time, we said that functional programming was marked by storing
% functions as variables (function handles) and working with functions that
% act on other functions. We put these ideas together to implement our own
% version of a |map| function for handling multiple inputs and outputs from
% multiple functions simultaneously, and we created |iif|, an "inline if",
% to allow the use of conditional statements inside of anonymous functions.
% So how might we work with recursive functions REPLACE_WITH_DASH_DASH functions of themselves?
% We'll see how a functional programming style allows us to implement
% recursive functionality inside anonymous functions, and this will pave
% the way for the final part, in which we'll implement loops, without ever 
% using |for| or |while| (which we can't use in anonymous functions).
% 
% Before we get started, let's implement |iif| again; we're going to need 
% it frequently.

iif = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();

%% Anonymous Function Recursion
% Recall that a recursive function is a function that calls itself. It 
% therefore needs some way to refer to itself. When we write an anonymous 
% function, it isn't "named" (hence, "anonymous"), so it can't call itself
% by name. How can we get around this?
%
% Let's start with a Fibonacci sequence example. Recall that the nth number
% of the Fibonacci sequence is the sum of the previous two numbers, 
% starting with 1 and 1, yielding 1, 1, 2, 3, 5, 8, 13, 21, etc. This is 
% easy to implement recursively.
%
%     fib = @(n) iif(n <= 2, 1, ...                    % First two numbers
%                    true,   @() fib(n-1) + fib(n-2)); % All later numbers
%
% But hey, that can't work! We haven't defined |fib| yet, so how could
% this anonymous function call it? In fact, the anonymous function will
% never "know" we're referring to it as |fib|, so this won't work at all. 
% Therefore, instead of trying to call |fib| directly, let's provide
% another input: the handle of a function to call, |f|.

fib = @(f, n) iif(n <= 2, 1, ...                      % First two numbers            
                  true,   @() f(f, n-1) + f(f, n-2)); % All later numbers

%%
% Getting closer. Now, if we pass |fib| _to_ |fib| along with the number we
% want, it will call |fib|, passing in |fib| as the first argument, 
% recursively until we get our answer.

fib(fib, 6)

%%
% Ok, that's right. The sixth number of the sequence is 8. On the other 
% hand, the syntax we've created is terrible. We have to provide the
% function to itself? I'd rather not. Instead, let's just write a new
% function that hands |fib| to |fib| along with the input |n|.

fib2 = @(n) fib(fib, n);

fib2(4)
fib2(5)
fib2(6)

%%
% That's a lot closer to what we want, but there's one more step. Let's
% write a function called |recur| to hand a function handle to itself, 
% along with any other arguments. This makes recursion less cumbersome.

recur = @(f, varargin) f(f, varargin{:});

%%
% That was simple, so now let's re-write |fib|. The first argument to
% |recur| is the function, which we'll define inline. The second is |n|.
% That's all there is to it. It now reads as "Recursively call a function
% that, if |k <= 2|, returns one, and otherwise returns the recursive
% function of |k-1| plus that of |k-2|, starting with the user's input
% |n|." (If it doesn't read quite this clearly at first, that's ok. It
% takes some getting used to. Comment liberally if necessary!)

fib = @(n) recur(@(f, k) iif(k <= 2, 1, ...
                             true,   @() f(f, k-1) + f(f, k-2)), ...
                 n);

%%
% And we can find the first ten numbers of the sequence via 
% <http://www.mathworks.com/help/matlab/ref/arrayfun.html arrayfun>.

arrayfun(fib, 1:10)

%%
% Factorial (f(n) = 1 * 2 * 3 * ... n) is another easy operation to 
% represent recursively.

factorial = @(n) recur(@(f, k) iif(k == 0, 1, ...
                                   true,   @() k * f(f, k-1)), n);
arrayfun(factorial, 1:7)

%%
% A number to an integer power has a nearly identical form. Here's 
% |4.^(0:5)|.

pow = @(x, n) recur(@(f, k) iif(k == 0, 1, ...
                                true,   @() x * f(f, k-1)), n);
arrayfun(@(n) pow(4, n), 0:5)

%%
% That was a big step for anonymous functions, using both recursion and an
% inline conditional together with ease. Like |map| and |iif|, |recur|, 
% looks strange at first, but once it's been seen, it's hard to forget how 
% it works (just make one of the inputs a function handle and pass it to 
% itself). And recursion doesn't have to stop at interesting mathematical 
% sequences of numbers. For instance, in the next part, we'll use this to 
% implement loops in, but first, we'll need a some helper functions and a
% good way to execute multiple statements in an anonymous function.

%% Helpers
% These little functions are useful in many circumstances, and we're going
% to need |curly| frequently.

paren = @(x, varargin) x(varargin{:});
curly = @(x, varargin) x{varargin{:}};

%%
% They allow us to write |x(3, 4)| as |paren(x, 3, 4)| and similarly for 
% curly braces. That is, now we can think of parentheses and curly braces 
% as functions! At first this might not seem useful. However, imagine 
% writing a function to return the width and height of the screen. The data
% we need is available from this call:

get(0, 'ScreenSize')

%%
% However, we don't need those preceeding ones. We could save the output to
% a variable, say |x|, and then access x(3:4), but if we need this in an
% anonymous function, we can't save to a variable. How do we access just
% elements 3 and 4? There are numerous ways, but |paren| and |curly| are
% similar to constructs found in other languages and are easy to use, so
% we'll use those here.
%
% Now we can write our |screen_size| function to return just the data we
% want.

screen_size = @() paren(get(0, 'ScreenSize'), 3:4);

screen_size()

%%
% While on the subject, note that we can actually use any number of
% indices or even ':'.

magic(3)
paren(magic(3), 1:2, 2:3)
paren(magic(3), 1:2, :)

%%
% We do the same with the curly braces. Here, the regular expression 
% pattern will match both 'rain' and 'Spain', but we'll only select the 
% second match.

spain = curly(regexp('The rain in Spain....', '\s(\S+ain)', 'tokens'), 2)

%%
% (Click for <http://www.mathworks.com/help/matlab/ref/regexp.html Regexp 
% help>.)

%%
% It also works with ':' (note that the single quotes are required).

[a, b] = curly({'the_letter_a', 'the_letter_b'}, ':')

%% Executing Multiple Statements
%
% With |curly| in place, let's examine something a little different.
% Consider the following:

do_three_things = @() {fprintf('This is the first thing.\n'), ...
                       fprintf('This is the second thing.\n'), ...
                       max(eig(magic(3)))};
                   
do_three_things()

%%
% We've executed three statements on a single line. All of the outputs are
% stored in the cell array, so we have three elements in the cell array.
% The first two outputs are actually garbage as far as we're concerned
% (they're just the outputs from |fprintf|, which is the number of 
% bytes written, which we don't care about at all). The last output is from
% |max(eig(magic(3)))|; That is, the biggest eigenvalue of |magic(3)| is 
% exactly 15. Let's say we just wanted that final value, the eigenvalue.
% It's the third element of the cell array, so we can grab it with |curly|.

do_three_things = @() curly({fprintf('This is the first thing.\n'), ...
                             fprintf('This is the second thing.\n'), ...
                             max(eig(magic(3)))}, 3);
                   
do_three_things()

%%
% For a more complex example, let's say we want to write a function to:
% 
% # Create a small figure in the middle of the screen
% # Plot some random points
% # Return the handles of the figure and the plot
%
% Then by storing all of the outputs in a cell array and using |curly| to
% access the outputs we care about, we can make a multi-line function with
% multiple outputs, all in a simple anonymous function.

dots = @() curly({...
    figure('Position', [0.5*screen_size() - [100 50], 200, 100], ...
           'MenuBar',  'none'), ...                % Position the figure
    plot(randn(1, 100), randn(1, 100), '.')}, ...  % Plot random points
    ':');                                          % Return everything

[h_figure, h_dots] = dots()

%%
% (As a quick aside, note that if a statement doesn't return anything, we
% can't put it in a cell array, and so we can't use it this way. There are
% ways around this, discussed 
% <http://www.mathworks.com/matlabcentral/fileexchange/39735-functional-programming-constructs here>.)

%% To Be Continued
% 
% Today, we've come a long way, from a simple condition through recursion
% and executing multiple statements. Here's a roundup of the functions so 
% far.

map     = @(val, fcns) cellfun(@(f) f(val{:}), fcns);
mapc    = @(val, fcns) cellfun(@(f) f(val{:}), fcns, 'UniformOutput', 0);
iif     = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();
recur   = @(f, varargin) f(f, varargin{:});
paren   = @(x, varargin) x(varargin{:});
curly   = @(x, varargin) x{varargin{:}};

%%
% These can also be found 
% <http://www.mathworks.com/matlabcentral/fileexchange/39735-functional-programming-constructs here>,
% implemented as regular MATLAB functions that can be kept on the path.

%%
% Next time, we'll look at loops. Until then, have you worked with 
% functions such as |paren| or |curly|? How else are people implementing 
% these or similar operations? Let us know <http://blogs.mathworks.com/loren/?p=611#respond here>.

##### SOURCE END ##### 785282659a42421c916b8b165e146cdb
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/pbQ7kUuN8gg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2013/01/24/introduction-to-functional-programming-with-anonymous-functions-part-2/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2013/01/24/introduction-to-functional-programming-with-anonymous-functions-part-2/</feedburner:origLink></item>
	</channel>
</rss>
