<?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>Mon, 14 May 2012 08:32:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.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>Why is Answer to 3 &lt; A &lt; 7 Unexpected?</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/QDJ0tF5vn9k/</link>
		<comments>http://blogs.mathworks.com/loren/2012/05/14/why-is-answer-to-3-a-7-unexpected/#comments</comments>
		<pubDate>Mon, 14 May 2012 08:32:02 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Common Errors]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=441</guid>
		<description><![CDATA[There have been countless (not really!) times on the MATLAB newsgroup where a question of the sort written in the title has been asked (and answered). Let's go through the code to understand what's happening. DISCLAIMER: It's not my intention in this post to discuss non-scalar behavior. Contents Problem Statement WHAT??? First Part of Expression: [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>There have been countless (not really!) times on the <a href="http://www.mathworks.com/matlabcentral/newsreader/">MATLAB newsgroup</a> where a question of the sort written in the title has been asked (and answered).  Let's go through the code to understand
         what's happening.
      </p>
      <p><b>DISCLAIMER:</b> It's not my intention in this post to discuss non-scalar behavior.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Problem Statement</a></li>
         <li><a href="#3">WHAT???</a></li>
         <li><a href="#4">First Part of Expression: low &lt; A</a></li>
         <li><a href="#6">Second Part of Expression: previous output &lt; high</a></li>
         <li><a href="#8">Look at the Types</a></li>
         <li><a href="#10">How to Get the Expected Answer</a></li>
         <li><a href="#12">Have Compound Expressions Caused You Problems?</a></li>
      </ul>
   </div>
   <h3>Problem Statement<a name="1"></a></h3>
   <p>As part of program, suppose we need to see if some value lies between two others. let's say <tt>A</tt> is the value we are checking at the limits are <tt>low=3</tt> and <tt>high=7</tt>.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">low = 3;
high = 7;</pre><p>Mathematically you might write this as</p><pre>  low &lt; A &lt; high</pre><p>Let's try that for <tt>A</tt> values both inside the range and outside to start. And let me place the expression into an anonymous function so I don't
      have to keep repeating it.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">myExpr = @(x) low &lt; x &lt; high;
inResult = myExpr(pi)
outResult = myExpr(17)</pre><pre style="font-style:oblique">inResult =
     1
outResult =
     1
</pre><h3>WHAT???<a name="3"></a></h3>
   <p>It can't be true that both <tt>pi</tt> and <tt>17</tt> lie between <tt>3</tt> and <tt>7</tt>.  So what's going on?  Let's dissect the expression.
   </p>
   <h3>First Part of Expression: low &lt; A<a name="4"></a></h3>
   <p>Let's look at the first part of the expression.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">step1In = low &lt; pi
step1Out = low &lt; 17</pre><pre style="font-style:oblique">step1In =
     1
step1Out =
     1
</pre><p>and we see that this is true for both of our inputs.</p>
   <h3>Second Part of Expression: previous output &lt; high<a name="6"></a></h3>
   <p>The second part of our expression uses the output from the first expression and continues from there.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">step2In = step1In &lt; high
step2Out = step1Out &lt; high</pre><pre style="font-style:oblique">step2In =
     1
step2Out =
     1
</pre><p>and we see that we get ones, or true, for both of these.  What's going on?</p>
   <h3>Look at the Types<a name="8"></a></h3><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">whos <span style="color: #A020F0">step1*</span></pre><pre style="font-style:oblique">  Name          Size            Bytes  Class      Attributes

  step1In       1x1                 1  logical              
  step1Out      1x1                 1  logical              

</pre><p>The results from step 1 are logical - are these numbers greater than <tt>low</tt>?  And the answers for both of our values is yes, or <tt>true</tt>, represented in MATLAB as logical values.  When we take these values as inputs in the second step, what happens is the <tt>true</tt> values are interpreted as numeric inputs with value 1.  And then we ask if 1 is less than <tt>high</tt>.  Which it is in both of these cases!
   </p>
   <h3>How to Get the Expected Answer<a name="10"></a></h3>
   <p>How do we get the expected answer, and it's easy.  We simply combine two logical expressions, but in a different way than
      above.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">myExprCorrect = @(x) (low &lt; x) &amp; (x &lt; high)
inResult1 = myExprCorrect(pi)
outResult1 = myExprCorrect(17)</pre><pre style="font-style:oblique">myExprCorrect = 
    @(x)(low&lt;x)&amp;(x&lt;high)
inResult1 =
     1
outResult1 =
     0
</pre><p>What we did is checked first to see if the number was greater than <tt>low</tt> and separately checked the same number with <tt>high</tt>.  After getting two logical answers, we combine them.  They must both be true for numbers that lie between <tt>low</tt> and <tt>high</tt> and hence the result should yield <tt>true</tt> only under those conditions.
   </p>
   <p>For what it's worth, I always use parentheses to group my expressions to make them very readable for me so I don't need to
      wonder later what I intended to be testing.
   </p>
   <h3>Have Compound Expressions Caused You Problems?<a name="12"></a></h3>
   <p>Let me know <a href="http://blogs.mathworks.com/loren/?p=441#respond">here</a> if you've had trouble with expressions like the one in this post.
   </p><script language="JavaScript">
<!--

    function grabCode_a61231a8b61a49bd915aae200c8438b7() {
        // 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='a61231a8b61a49bd915aae200c8438b7 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' a61231a8b61a49bd915aae200c8438b7';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

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

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_a61231a8b61a49bd915aae200c8438b7()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.14<br /></p>
</div>
<!--
a61231a8b61a49bd915aae200c8438b7 ##### SOURCE BEGIN #####
%% Why is Answer to 3 < A < 7 Unexpected?
% There have been countless (not really!) times on the
% <http://www.mathworks.com/matlabcentral/newsreader/ MATLAB newsgroup>
% where a question of the sort written in the title has been asked (and
% answered).  Let's go through the code to understand what's happening.
%
% *DISCLAIMER:* It's not my intention in this post to discuss non-scalar
% behavior.
%% Problem Statement
% As part of program, suppose we need to see if some value lies between two
% others. let's say |A| is the value we are checking at the limits are
% |low=3| and |high=7|.
low = 3;
high = 7;
%%
% Mathematically you might write this as
%
%    low < A < high
%
% Let's try that for |A| values both inside the range and outside to start.
% And let me place the expression into an anonymous function so I don't
% have to keep repeating it.
myExpr = @(x) low < x < high;
inResult = myExpr(pi)
outResult = myExpr(17)
%% WHAT???
% It can't be true that both |pi| and |17| lie between |3| and |7|.  So
% what's going on?  Let's dissect the expression.
%
%% First Part of Expression: low < A
% Let's look at the first part of the expression.
step1In = low < pi
step1Out = low < 17
%%
% and we see that this is true for both of our inputs.
%% Second Part of Expression: previous output < high
% The second part of our expression uses the output from the first
% expression and continues from there.
step2In = step1In < high
step2Out = step1Out < high
%%
% and we see that we get ones, or true, for both of these.  What's going
% on?  
%% Look at the Types
whos step1*
%%
% The results from step 1 are logical - are these numbers greater than
% |low|?  And the answers for both of our values is yes, or |true|,
% represented in MATLAB as logical values.  When we take these values as
% inputs in the second step, what happens is the |true| values are
% interpreted as numeric inputs with value 1.  And then we ask if 1 is less
% than |high|.  Which it is in both of these cases!
%% How to Get the Expected Answer
% How do we get the expected answer, and it's easy.  We simply combine two
% logical expressions, but in a different way than above.
myExprCorrect = @(x) (low < x) &#038; (x < high)
inResult1 = myExprCorrect(pi)
outResult1 = myExprCorrect(17)
%%
% What we did is checked first to see if the number was greater than |low|
% and separately checked the same number with |high|.  After getting two
% logical answers, we combine them.  They must both be true for numbers
% that lie between |low| and |high| and hence the result should yield
% |true| only under those conditions.
%
% For what it's worth, I always use parentheses to group my expressions to
% make them very readable for me so I don't need to wonder later what I
% intended to be testing.
%% Have Compound Expressions Caused You Problems?
% Let me know <http://blogs.mathworks.com/loren/?p=441#respond here> if you've had trouble with expressions like the one
% in this post.
##### SOURCE END ##### a61231a8b61a49bd915aae200c8438b7
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/QDJ0tF5vn9k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/05/14/why-is-answer-to-3-a-7-unexpected/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/05/14/why-is-answer-to-3-a-7-unexpected/</feedburner:origLink></item>
		<item>
		<title>Mathematics and Humanities: Understanding Sort Algorithms</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/KrJGJ7z0i-c/</link>
		<comments>http://blogs.mathworks.com/loren/2012/04/27/mathematics-and-humanities-understanding-sort-algorithms/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 10:00:12 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Fun]]></category>
		<category><![CDATA[How To]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=428</guid>
		<description><![CDATA[Steve recently mentioned a video showing how the quiksort algorithm works, including an explanation from Bobby regarding the need for the final seconds to be sure that NaN values are sorted correctly. Contents Visualizing Quiksort Visualizing Other Sort Algorithms A Place Where Math Meets the Humanities Visualizing Quiksort With much amusement, many of us from [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>Steve <a href="http://blogs.mathworks.com/steve/2012/04/11/and-now-for-something-completely-different/">recently mentioned a video</a> showing how the <a href="http://en.wikipedia.org/wiki/Quicksort">quiksort</a> algorithm works, including an explanation from Bobby regarding the need for the final seconds to be sure that <tt>NaN</tt> values are sorted correctly.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Visualizing Quiksort</a></li>
         <li><a href="#2">Visualizing Other Sort Algorithms</a></li>
         <li><a href="#3">A Place Where Math Meets the Humanities</a></li>
      </ul>
   </div>
   <h3>Visualizing Quiksort<a name="1"></a></h3>
   <p>With much amusement, many of us from MathWorks recently viewed <a href="http://www.youtube.com/watch?v=ywWBy6J5gz8&amp;feature=share">this video</a> depicting the quiksort algorithm in dance.  I don't think you'll see a MATLAB animation quite like this!
   </p>
   <h3>Visualizing Other Sort Algorithms<a name="2"></a></h3>
   <p>If you are interested in similar visual depictions of other sorting algorithms, check out <a href="http://www.youtube.com/user/AlgoRythmics">this link</a>.
   </p>
   <h3>A Place Where Math Meets the Humanities<a name="3"></a></h3>
   <p>In addition to these animations showing off mathematical algorithms, I have also enjoyed listening to and trying my hand at
      <a href="http://en.wikipedia.org/wiki/Change_ringing">change ringing</a>.  I find similar points of intersection between my love of math and my interest in other art forms as well.  Also check out
      the <a href="http://en.wikipedia.org/wiki/Wallpaper_group">17 regular tilings of the plane</a>.
   </p>
   <p>Do you have similar links between some interesting math and art?  Let me know <a href="http://blogs.mathworks.com/loren/?p=428#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_8b49bbae548d475290e3aaeb35c4b4e9() {
        // 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='8b49bbae548d475290e3aaeb35c4b4e9 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 8b49bbae548d475290e3aaeb35c4b4e9';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

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

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_8b49bbae548d475290e3aaeb35c4b4e9()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.14<br /></p>
</div>
<!--
8b49bbae548d475290e3aaeb35c4b4e9 ##### SOURCE BEGIN #####
%% Mathematics and Humanities: Understanding Sort Algorithms
% Steve
% <http://blogs.mathworks.com/steve/2012/04/11/and-now-for-something-completely-different/
% recently mentioned a video> showing how the
% <http://en.wikipedia.org/wiki/Quicksort quiksort> algorithm works,
% including an explanation from Bobby regarding the need for the final
% seconds to be sure that |NaN| values are sorted correctly.
%% Visualizing Quiksort
% With much amusement, many of us from MathWorks recently viewed
% <http://www.youtube.com/watch?v=ywWBy6J5gz8&#038;feature=share this video>
% depicting the quiksort algorithm in dance.  I don't think you'll see a
% MATLAB animation quite like this!
%% Visualizing Other Sort Algorithms
% If you are interested in similar visual depictions of other sorting
% algorithms, check out <http://www.youtube.com/user/AlgoRythmics this
% link>.
%% A Place Where Math Meets the Humanities
% In addition to these animations showing off mathematical algorithms, I
% have also enjoyed listening to and trying my hand at
% <http://en.wikipedia.org/wiki/Change_ringing change ringing>.  I find
% similar points of intersection between my love of math and my interest in
% other art forms as well.  Also check out the
% <http://en.wikipedia.org/wiki/Wallpaper_group 17 regular tilings of the
% plane>.
%
% Do you have similar links between some interesting math and art?  Let me
% know <http://blogs.mathworks.com/loren/?p=428#respond here>.
##### SOURCE END ##### 8b49bbae548d475290e3aaeb35c4b4e9
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/KrJGJ7z0i-c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/04/27/mathematics-and-humanities-understanding-sort-algorithms/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/04/27/mathematics-and-humanities-understanding-sort-algorithms/</feedburner:origLink></item>
		<item>
		<title>Running Scripts on a Cluster Using the Batch Command in Parallel Computing Toolbox</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/DTsiwiZE4H0/</link>
		<comments>http://blogs.mathworks.com/loren/2012/04/20/running-scripts-on-a-cluster-using-the-batch-command-in-parallel-computing-toolbox/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 09:22:43 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Parallel]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=397</guid>
		<description><![CDATA[I'd like to introduce this week's guest blogger Edric Ellis. Edric works for the Parallel Computing development team here at The MathWorks. In this post he will talk about using the batch command in Parallel Computing Toolbox. Sometimes, even when you've optimized your MATLAB&#174; code, you find that you have so many simulations to run, [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>I'd like to introduce this week's guest blogger <a href="http://www.mathworks.com/matlabcentral/answers/contributors/1287414-edric-ellis">Edric Ellis</a>. Edric works for the Parallel Computing development team here at The MathWorks. In this post he will talk about using the
         batch command in Parallel Computing Toolbox.
      </p>
      <p>Sometimes, even when you've optimized your MATLAB&reg; code, you find that you have so many simulations to run, or scenarios to
         explore, that running them on your desktop computer just takes too long. <a href="http://www.mathworks.com/products/parallel-computing/">Parallel Computing Toolbox&#8482;</a> together with <a href="http://www.mathworks.com/products/distriben/">MATLAB Distributed Computing Server&#8482;</a> can help you to run your scripts and functions on a cluster of computers. As well as running on a remote cluster, Parallel
         Computing Toolbox lets you use the cores in your desktop machine as a simple local cluster. This article is going to show
         how to use this local cluster - but once you've got things working on the "local" cluster, it is simple to scale up to running
         your scripts on a remote cluster.
      </p>
      <p>The problem we're going to look at is a Monte-Carlo simulation of a financial instrument - the expected returns from playing
         hands of <a href="http://en.wikipedia.org/wiki/Blackjack">blackjack</a> in a casino. We'll approach the problem in three phases:
      </p>
      <li>Running the Blackjack Simulation in MATLAB</li>
      <li>Submitting Batch Jobs to Run Blackjack on the "local" Cluster</li>
      <li>Adding <tt>parfor</tt> Loops to the Script
      </li>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Running the Blackjack Simulation in MATLAB</a></li>
         <li><a href="#2">Running Blackjack as a Script Directly in MATLAB</a></li>
         <li><a href="#3">Submitting Batch Jobs to Run Blackjack on the "local" Cluster</a></li>
         <li><a href="#4">Adding parfor Loops to the Script</a></li>
         <li><a href="#5">Running the parfor script with an open MATLAB pool</a></li>
         <li><a href="#6">Running a Batch Job Containing a parfor Loop</a></li>
         <li><a href="#7">Conclusions</a></li>
      </ul>
   </div>
   <h3>Running the Blackjack Simulation in MATLAB<a name="1"></a></h3>
   <p>The calculation of the result of playing a single hand of blackjack was written by <a href="http://www.mathworks.com/company/aboutus/founders/clevemoler.html">Cleve Moler</a>, and is available on the <a href="http://www.mathworks.com/matlabcentral/fileexchange/4404-blackjack">file exchange</a>. During this article, we're going to use a slightly modified version of that program where we've extracted just the calculation
      of a single hand of blackjack so that we can invoke it in a variety of different ways. There's a discussion of the algorithm
      in chapter 9 of <a href="http://www.mathworks.com/moler/index_ncm.html">Cleve's book "Numerical Computing with MATLAB"</a>.
   </p>
   <p>Cleve describes the amount won playing a single hand of blackjack as follows:</p>
   <p><i>"[win] zero for a 'push', win $15 for a blackjack, win or lose $10 on a hand that has not been split or doubled, win or lose
         $20 on hands that have been split or doubled once, and win or lose $30 or $40 on hands that have been doubled after a split.
         The $30 and $40 payoffs occur rarely (and may not be allowed at some casinos)."</i></p>
   <p>We can calculate the winnings of playing several individual hands of blackjack simply by invoking <tt>blackjack_kernel</tt> a few times.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">winnings = zeros(1,10);
<span style="color: #0000FF">for</span> ii=1:10
    winnings(ii) = blackjack_kernel;
<span style="color: #0000FF">end</span>
winnings</pre><pre style="font-style:oblique">
winnings =

    15   -10     0     0   -10    10   -10   -10   -10    10

</pre><h3>Running Blackjack as a Script Directly in MATLAB<a name="2"></a></h3>
   <p>The script <tt>blackjack_script</tt> simulates a number of players playing many hands of blackjack, and computes for each player their net profit after those
      hands. Let's run the script and then plot the results as a histogram showing the distribution of profit and loss among the
      players.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">blackjack_script</span>

blackjack_script;
hist(results);
title(<span style="color: #A020F0">'Profit and loss playing blackjack'</span>);
xlabel(<span style="color: #A020F0">'Profit'</span>); ylabel(<span style="color: #A020F0">'Count'</span>);</pre><pre style="font-style:oblique">
numHands   = 500;
numPlayers = 50;
results    = zeros(1, numPlayers);
tic
for h = 1:numHands
    thisHand = zeros(1, numPlayers);
    for p = 1:numPlayers
        thisHand(p) = blackjack_kernel;
    end
    results = results + thisHand;
end
t = toc;
fprintf('Time to simulate %d players playing %d hands of blackjack: %.3g seconds\n', ...
        numPlayers, numHands, t);

Time to simulate 50 players playing 500 hands of blackjack: 8.04 seconds
</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/397/batchblog_01.png"> <h3>Submitting Batch Jobs to Run Blackjack on the "local" Cluster<a name="3"></a></h3>
   <p>Now that our script works correctly, we can submit the script for execution on a cluster. In this case, we're going to use
      the "local" cluster since it's always available, but you might submit the script for execution on a remote cluster if you
      have one available. When you do submit to a remote cluster, you're free to close down your MATLAB session and collect the
      results later. If you're using the local cluster, you can carry on using your MATLAB session while the batch job runs in the
      background; also, you can have several batch jobs running simultaneously.
   </p>
   <p>We invoke the <a href="http://www.mathworks.com/help/toolbox/distcomp/batch.html"><tt>batch</tt></a> command with the name of the script we wish to run, and here we're also specifying which <a href="http://www.mathworks.com/help/toolbox/distcomp/f5-16141.html"><tt>'Profile'</tt></a> we wish to use. Profiles identify connections you have made to different clusters that might be available, the 'local' profile
      is always available. Other cluster types require an MDCS installation. If you only have a single Profile, you don't need to
      specify the Profile argument. The return from the <tt>batch</tt> command is a job object. The job object allows us to track the progress of execution on the cluster, and when it has finished,
      we can access the results.
   </p>
   <p>As well as using the <tt>batch</tt> command directly from the MATLAB command line, you can right-click on a script file in MATLAB's Current Folder browser, and
      select <a href="http://www.mathworks.com/help/toolbox/distcomp/rn/bs15q67.html#bs3_a0p-1">"Run Script as Batch Job"</a>. This uses your default cluster profile.
   </p>
   <p>In this example, the first thing that we do with the job is call <tt>wait</tt> so that we only proceed when the job has finished executing. Alternatively, you can carry on working in MATLAB and check
      the state of the job by looking at <tt>job.State</tt>, loading the results when the state is <tt>'finished'</tt>.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">job = batch(<span style="color: #A020F0">'blackjack_script'</span>, <span style="color: #A020F0">'Profile'</span>, <span style="color: #A020F0">'local'</span>);

<span style="color: #228B22">% Wait for the job to complete execution.</span>
wait(job);

<span style="color: #228B22">% Load the results of executing the job into the MATLAB workspace</span>
load(job);

<span style="color: #228B22">% And display the diary output from the job</span>
disp(<span style="color: #A020F0">'Diary output from the batch job:'</span>)
diary(job);

<span style="color: #228B22">% We can plot the results as we did previously.</span>
hist(results);
title(<span style="color: #A020F0">'Profit and loss playing blackjack'</span>);
xlabel(<span style="color: #A020F0">'Profit'</span>); ylabel(<span style="color: #A020F0">'Count'</span>);</pre><pre style="font-style:oblique">Diary output from the batch job:
Time to simulate 50 players playing 500 hands of blackjack: 7.93 seconds

</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/397/batchblog_02.png"> <h3>Adding parfor Loops to the Script<a name="4"></a></h3>
   <p>Running a batch job on the local machine doesn't make things go any quicker, although running a job on a remote cluster might
      give you access to a more powerful machine. Even on the local machine, we can still use <a href="http://www.mathworks.com/help/toolbox/distcomp/f5-16141.html"><tt>parfor</tt></a> to gain a speedup. Each iteration of the outer <tt>for</tt> loop in <tt>blackjack_script</tt> is independent, and the calculation of <tt>results</tt> is a "reduction" or summary operation that <tt>parfor</tt> can understand. So, we can recast the script into a variant using <tt>parfor</tt> simply by changing the outer loop:
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">blackjack_script_parfor</span></pre><pre style="font-style:oblique">
numHands   = 500;
numPlayers = 50;
results    = zeros(1, numPlayers);
tic
parfor h = 1:numHands
    thisHand = zeros(1, numPlayers);
    for p = 1:numPlayers
        thisHand(p) = blackjack_kernel;
    end
    results = results + thisHand;
end
t = toc;
fprintf('Time to simulate %d players playing %d hands of blackjack: %.3g seconds\n', ...
        numPlayers, numHands, t);


</pre><h3>Running the parfor script with an open MATLAB pool<a name="5"></a></h3>
   <p>We can check that the <tt>parfor</tt> loop is working correctly by opening an interactive <tt>matlabpool</tt> session. An interactive <a href="http://www.mathworks.com/help/toolbox/distcomp/matlabpool.html">matlabpool</a> session launches workers based on the Profile you specify, and makes them available to your MATLAB session for running the
      body of <tt>parfor</tt> loops. Normally, it's a good idea to leave <tt>matlabpool</tt> open while you're working, but we're going to close it just after running the script to free up workers so that we can run
      a batch job.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)"><span style="color: #228B22">% Open matlabpool using the 'local' profile</span>
matlabpool <span style="color: #A020F0">open</span> <span style="color: #A020F0">local</span>

<span style="color: #228B22">% Run our script</span>
blackjack_script_parfor

<span style="color: #228B22">% Close the pool again to free up workers for when we run the batch job</span>
matlabpool <span style="color: #A020F0">close</span></pre><pre style="font-style:oblique">Starting matlabpool using the 'local' profile ... connected to 6 labs.
Time to simulate 50 players playing 500 hands of blackjack: 1.87 seconds
Sending a stop signal to all the labs ... stopped.
</pre><h3>Running a Batch Job Containing a parfor Loop<a name="6"></a></h3>
   <p>To run a batch job where a <tt>parfor</tt> loop is used, we need to specify an additional argument to the <tt>batch</tt> command - <tt>'Matlabpool'</tt>. The value of the option specifies how many <b>additional</b> workers to use when running the script. The machine I'm using has 6 cores, so I can run 1 worker to control the script execution,
      and 5 additional workers to act as a <a href="http://www.mathworks.com/help/toolbox/distcomp/matlabpool.html"><tt>matlabpool</tt></a>. These additional workers operate on the body of the <tt>parfor</tt> loop in parallel to calculate the result more quickly.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">job = batch(<span style="color: #A020F0">'blackjack_script_parfor'</span>, <span style="color: #0000FF">...</span><span style="color: #228B22"> % Run the script containing parfor</span>
            <span style="color: #A020F0">'Profile'</span>, <span style="color: #A020F0">'local'</span>, <span style="color: #0000FF">...</span><span style="color: #228B22">        % using the 'local' profile</span>
            <span style="color: #A020F0">'Matlabpool'</span>, 5);              <span style="color: #228B22">% with a Matlabpool of size 5</span>

<span style="color: #228B22">% Wait for the job to complete execution.</span>
wait(job);

<span style="color: #228B22">% Load the results of executing the job into the MATLAB workspace</span>
load(job);

<span style="color: #228B22">% And display the diary output from the job</span>
disp(<span style="color: #A020F0">'Diary output from the batch job using parfor:'</span>)
diary(job);

<span style="color: #228B22">% We can plot the results as we did previously.</span>
hist(results);
title(<span style="color: #A020F0">'Profit and loss playing blackjack'</span>);
xlabel(<span style="color: #A020F0">'Profit'</span>); ylabel(<span style="color: #A020F0">'Count'</span>);</pre><pre style="font-style:oblique">Diary output from the batch job using parfor:
Time to simulate 50 players playing 500 hands of blackjack: 1.92 seconds

</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/397/batchblog_03.png"> <h3>Conclusions<a name="7"></a></h3>
   <p>We have seen how using the <tt>batch</tt> command, we can send a script to be executed on a cluster. We've used the 'local' cluster here, which is a part of Parallel
      Computing Toolbox, but we could have just as easily used a remote cluster if a MATLAB Distributed Computing Server installation
      was available to us. Using a remote cluster allows even more compute resources to be used during the execution of a job. Some
      <tt>for</tt> loops (where each iteration can be executed independently of the others) lend themselves to parallel execution using <tt>parfor</tt>, and we saw how we can run a <tt>batch</tt> job where our script contained a <tt>parfor</tt> loop.
   </p>
   <p>There are more details about getting your code running on a cluster in the <a href="http://www.mathworks.com/help/toolbox/distcomp/">documentation</a>. Do you have any other questions about running your code on a cluster? Let us know <a href="http://blogs.mathworks.com/loren/?p=397#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_4a0364ff842e46d0b3edc19a192153c5() {
        // 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='4a0364ff842e46d0b3edc19a192153c5 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 4a0364ff842e46d0b3edc19a192153c5';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

        author = '';
        copyright = 'Copyright 2012 The MathWorks, Inc.';

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_4a0364ff842e46d0b3edc19a192153c5()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.14<br /></p>
</div>
<!--
4a0364ff842e46d0b3edc19a192153c5 ##### SOURCE BEGIN #####
%% Running Scripts on a Cluster Using the Batch Command in Parallel Computing Toolbox
% I'd like to introduce this week's guest blogger
% <http://www.mathworks.com/matlabcentral/answers/contributors/1287414-edric-ellis Edric Ellis>. 
% Edric works for the Parallel Computing development team here at
% The MathWorks. In this post he will talk about using the batch command in
% Parallel Computing Toolbox.
%
% Sometimes, even when you've optimized your MATLAB(R) code, you find that you have
% so many simulations to run, or scenarios to explore, that running them on your
% desktop computer just takes too long. <http://www.mathworks.com/products/parallel-computing/ Parallel Computing Toolbox(TM)> together with
% <http://www.mathworks.com/products/distriben/ MATLAB Distributed Computing Server(TM)> can help you to run your
% scripts and functions on a cluster of computers. As well as running on a
% remote cluster, Parallel Computing Toolbox lets you use the cores in your
% desktop machine as a simple local cluster. This article is going to show how to
% use this local cluster - but once you've got things working on the "local"
% cluster, it is simple to scale up to running your scripts on a remote
% cluster.
%
% The problem we're going to look at is a Monte-Carlo simulation of a financial
% instrument - the expected returns from playing hands of <http://en.wikipedia.org/wiki/Blackjack blackjack> in a
% casino. We'll approach the problem in three phases:
%
% # Running the Blackjack Simulation in MATLAB
% # Submitting Batch Jobs to Run Blackjack on the "local" Cluster
% # Adding |parfor| Loops to the Script
%
%% Running the Blackjack Simulation in MATLAB
% The calculation of the result of playing a single hand of blackjack was
% written by <http://www.mathworks.com/company/aboutus/founders/clevemoler.html Cleve Moler>, and is available on the <http://www.mathworks.com/matlabcentral/fileexchange/4404-blackjack file exchange>.
% During this article, we're going to use a slightly modified version
% of that program where we've extracted just the calculation of a single hand
% of blackjack so that we can invoke it in a variety of different ways. There's
% a discussion of the algorithm in chapter 9 of <http://www.mathworks.com/moler/index_ncm.html Cleve's book "Numerical Computing with MATLAB">.
%
% Cleve describes the amount won playing a single hand of blackjack as follows:
%
% _"[win] zero for a 'push', win $15 for a blackjack, win or lose $10 on a hand
% that has not been split or doubled, win or lose $20 on hands that have been
% split or doubled once, and win or lose $30 or $40 on hands that have been
% doubled after a split. The $30 and $40 payoffs occur rarely (and may not be
% allowed at some casinos)."_
%
% We can calculate the winnings of playing several individual hands of blackjack
% simply by invoking |blackjack_kernel| a few times.

winnings = zeros(1,10);
for ii=1:10
    winnings(ii) = blackjack_kernel;
end
winnings

%% Running Blackjack as a Script Directly in MATLAB
% The script |blackjack_script| simulates a number of players playing many hands
% of blackjack, and computes for each player their net profit after those hands.
% Let's run the script and then plot the results as a histogram showing the
% distribution of profit and loss among the players.

type blackjack_script

blackjack_script;
hist(results);
title('Profit and loss playing blackjack');
xlabel('Profit'); ylabel('Count');

%% Submitting Batch Jobs to Run Blackjack on the "local" Cluster
% Now that our script works correctly, we can submit the script for execution on
% a cluster. In this case, we're going to use the "local" cluster since it's
% always available, but you might submit the script for execution on a remote
% cluster if you have one available. When you do submit to a remote cluster,
% you're free to close down your MATLAB session and collect the results
% later. If you're using the local cluster, you can carry on using your MATLAB
% session while the batch job runs in the background; also, you can have several
% batch jobs running simultaneously.
%
% We invoke the <http://www.mathworks.com/help/toolbox/distcomp/batch.html |batch|> command with the name of the script we wish to run, and
% here we're also specifying which <http://www.mathworks.com/help/toolbox/distcomp/f5-16141.html |'Profile'|> we wish to use. Profiles identify
% connections you have made to different clusters that might be available, the
% 'local' profile is always available. Other cluster types require an MDCS installation. 
% If you only have a single Profile, you
% don't need to specify the Profile argument. The return from the |batch|
% command is a job object. The job object allows us to track the progress of
% execution on the cluster, and when it has finished, we can access the results.
%
% As well as using the |batch| command directly from the MATLAB command line,
% you can right-click on a script file in MATLAB's Current Folder browser, and select
% <http://www.mathworks.com/help/toolbox/distcomp/rn/bs15q67.html#bs3_a0p-1 "Run Script as Batch Job">. This uses your default cluster profile.
%
% In this example, the first thing that we do with the job is call |wait| so
% that we only proceed when the job has finished executing. Alternatively, you
% can carry on working in MATLAB and check the state of the job by looking at
% |job.State|, loading the results when the state is |'finished'|.

job = batch('blackjack_script', 'Profile', 'local');

% Wait for the job to complete execution.
wait(job);

% Load the results of executing the job into the MATLAB workspace
load(job);

% And display the diary output from the job
disp('Diary output from the batch job:')
diary(job);

% We can plot the results as we did previously.
hist(results);
title('Profit and loss playing blackjack');
xlabel('Profit'); ylabel('Count');


%% Adding |parfor| Loops to the Script
% Running a batch job on the local machine doesn't make things go any quicker,
% although running a job on a remote cluster might give you access to a more
% powerful machine. Even on the local machine, we can still use <http://www.mathworks.com/help/toolbox/distcomp/f5-16141.html |parfor|> to gain
% a speedup. Each iteration of the outer |for| loop in |blackjack_script| is
% independent, and the calculation of |results| is a "reduction" or summary
% operation that |parfor| can understand. So, we can recast the script into a
% variant using |parfor| simply by changing the outer loop:

type blackjack_script_parfor

%% Running the |parfor| script with an open MATLAB pool
% We can check that the |parfor| loop is working correctly by opening an
% interactive |matlabpool| session. An interactive <http://www.mathworks.com/help/toolbox/distcomp/matlabpool.html matlabpool> session launches
% workers based on the Profile you specify, and makes them available to your
% MATLAB session for running the body of |parfor| loops. Normally, it's a good
% idea to leave |matlabpool| open while you're working, but we're going to close
% it just after running the script to free up workers so that we can run a batch
% job.

% Open matlabpool using the 'local' profile
matlabpool open local

% Run our script
blackjack_script_parfor

% Close the pool again to free up workers for when we run the batch job
matlabpool close

%% Running a Batch Job Containing a parfor Loop
% To run a batch job where a |parfor| loop is used, we need to specify an
% additional argument to the |batch| command - |'Matlabpool'|. The value of the
% option specifies how many *additional* workers to use when running the
% script. The machine I'm using has 6 cores, so I can run 1 worker to control the script
% execution, and 5 additional workers to act as a <http://www.mathworks.com/help/toolbox/distcomp/matlabpool.html |matlabpool|>. These additional
% workers operate on the body of the |parfor| loop in parallel to calculate the
% result more quickly.

job = batch('blackjack_script_parfor', ... % Run the script containing parfor
            'Profile', 'local', ...        % using the 'local' profile
            'Matlabpool', 5);              % with a Matlabpool of size 5

% Wait for the job to complete execution.
wait(job);

% Load the results of executing the job into the MATLAB workspace
load(job);

% And display the diary output from the job
disp('Diary output from the batch job using parfor:')
diary(job);

% We can plot the results as we did previously.
hist(results);
title('Profit and loss playing blackjack');
xlabel('Profit'); ylabel('Count');

%% Conclusions
% We have seen how using the |batch| command, we can send a script to be
% executed on a cluster. We've used the 'local' cluster here, which is a part of
% Parallel Computing Toolbox, but we could have just as easily used a remote
% cluster if a MATLAB Distributed Computing Server installation was available to
% us. Using a remote cluster allows even more compute resources to be used
% during the execution of a job. Some |for| loops (where each iteration can be
% executed independently of the others) lend themselves to parallel execution
% using |parfor|, and we saw how we can run a |batch| job where our script
% contained a |parfor| loop.
%
% There are more details about getting your code running on a cluster in the
% <http://www.mathworks.com/help/toolbox/distcomp/ documentation>. Do you have any other questions about running your code on a
% cluster? Let us know <http://blogs.mathworks.com/loren/?p=397#respond here>.

##### SOURCE END ##### 4a0364ff842e46d0b3edc19a192153c5
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/DTsiwiZE4H0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/04/20/running-scripts-on-a-cluster-using-the-batch-command-in-parallel-computing-toolbox/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/04/20/running-scripts-on-a-cluster-using-the-batch-command-in-parallel-computing-toolbox/</feedburner:origLink></item>
		<item>
		<title>Have You Visited MATLAB Central Recently?</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/X2_AIt-qGPA/</link>
		<comments>http://blogs.mathworks.com/loren/2012/04/10/have-you-visited-matlab-central-recently/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 13:11:20 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=421</guid>
		<description><![CDATA[I don't know if you visit MATLAB Central often, but there's a good reason to these days. Contents New at MATLAB Central Which Community Service Do You Use Most? New at MATLAB Central In addition to the usual services on MATLAB Central, File Exchange: download and share files Link Exchange: share resource Newsgroup: read and [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>I don't know if you visit <a href="http://www.mathworks.com/matlabcentral/">MATLAB Central</a> often, but there's a good reason to these days.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">New at MATLAB Central</a></li>
         <li><a href="#2">Which Community Service Do You Use Most?</a></li>
      </ul>
   </div>
   <h3>New at MATLAB Central<a name="1"></a></h3>
   <p>In addition to the usual services on MATLAB Central,</p>
   <div>
      <ul>
         <li><a href="http://www.mathworks.com/matlabcentral/">File Exchange</a>: download and share files
         </li>
         <li><a href="http://www.mathworks.com/matlabcentral/linkexchange/">Link Exchange</a>: share resource
         </li>
         <li><a href="http://www.mathworks.com/matlabcentral/newsreader/">Newsgroup</a>: read and post to the Usenet newsgroup <tt>comp-soft-sys.matlab</tt></li>
      </ul>
   </div>
   <p>there are three new additions to MATLAB Central collection.  I'll list them here and delve into more details in later posts.</p>
   <p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/421/mlcentral.png"> </p>
   <div>
      <ul>
         <li><a href="http://www.mathworks.com/matlabcentral/answers/">MATLAB Answers</a>: ask and answer MATLAB questions
         </li>
         <li><a href="http://www.mathworks.com/matlabcentral/cody">Cody</a>: solve and ask MATLAB problems (with code)
         </li>
         <li><a href="http://www.mathworks.com/matlabcentral/trendy">Trendy</a>: display trends of interesting information
         </li>
      </ul>
   </div>
   <h3>Which Community Service Do You Use Most?<a name="2"></a></h3>
   <p>I'm wondering which service you use most.  Let me know <a href="http://blogs.mathworks.com/loren/?p=421#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_791ae46cf6714d32832dd9c9d216b1da() {
        // 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='791ae46cf6714d32832dd9c9d216b1da ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 791ae46cf6714d32832dd9c9d216b1da';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

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

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_791ae46cf6714d32832dd9c9d216b1da()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.14<br /></p>
</div>
<!--
791ae46cf6714d32832dd9c9d216b1da ##### SOURCE BEGIN #####
%% Have You Visited MATLAB Central Recently?
% I don't know if you visit <http://www.mathworks.com/matlabcentral/ MATLAB
% Central> often, but there's a good reason to these days.
%% New at MATLAB Central
% In addition to the usual services on MATLAB Central,
%
% * <http://www.mathworks.com/matlabcentral/ File Exchange>: download and
% share files
% * <http://www.mathworks.com/matlabcentral/linkexchange/ Link Exchange>:
% share resource
% * <http://www.mathworks.com/matlabcentral/newsreader/ Newsgroup>: read
% and post to the Usenet newsgroup |comp-soft-sys.matlab|
%
% there are three new additions to MATLAB Central collection.  I'll list
% them here and delve into more details in later posts.
%
% <<mlcentral.png>> 
%
% * <http://www.mathworks.com/matlabcentral/answers/ MATLAB Answers>: ask
% and answer MATLAB questions
% * <http://www.mathworks.com/matlabcentral/cody Cody>: solve and ask
% MATLAB problems (with code)
% * <http://www.mathworks.com/matlabcentral/trendy Trendy>: display trends
% of interesting information
%
%% Which Community Service Do You Use Most?
% I'm wondering which service you use most.  Let me know
% <http://blogs.mathworks.com/loren/?p=421#respond here>.


##### SOURCE END ##### 791ae46cf6714d32832dd9c9d216b1da
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/X2_AIt-qGPA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/04/10/have-you-visited-matlab-central-recently/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/04/10/have-you-visited-matlab-central-recently/</feedburner:origLink></item>
		<item>
		<title>Considering Performance in Object-Oriented MATLAB Code</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/REziEzN7JwY/</link>
		<comments>http://blogs.mathworks.com/loren/2012/03/26/considering-performance-in-object-oriented-matlab-code/#comments</comments>
		<pubDate>Mon, 26 Mar 2012 13:35:15 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Object-oriented]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=391</guid>
		<description><![CDATA[I&#8217;m pleased to have Dave Foti back for a look at objects and performance. Dave manages the group responsible for object-oriented programming features in MATLAB. I often get questions along the lines of what performance penalty is paid for using objects or how fast will an object-oriented implementation perform compared with some other implementation. As [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>I&#8217;m pleased to have Dave Foti back for a look at objects and performance. Dave manages the group responsible for object-oriented
         programming features in MATLAB.
      </p>
      <p>I often get questions along the lines of what performance penalty is paid for using objects or how fast will an object-oriented
         implementation perform compared with some other implementation.  As with many performance questions, the answer is that it
         very much depends on what the program is trying to do and what parts of its work are most performance-intensive.  I see many
         cases where most of the real work is inside methods of an object that do math on ordinary matrices.  Such applications won&#8217;t
         really see much difference with or without objects.  I also realize that many MATLAB users aren&#8217;t nearly as concerned with
         run-time performance as with how long it takes to write the program. However, for those applications where performance matters
         and objects might be used in performance critical parts of the application, let&#8217;s look at what can we say about how MATLAB
         works that might be helpful to consider.  We&#8217;ll also look at what has changed in recent MATLAB versions.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">How objects spend their time</a></li>
         <li><a href="#2">Object Construction</a></li>
         <li><a href="#3">Property Access</a></li>
         <li><a href="#8">Optimizing for Property Usage Inside the Class</a></li>
         <li><a href="#11">Method Invocation</a></li>
         <li><a href="#16">Deleting Handle Objects</a></li>
         <li><a href="#21">A Look to the Future</a></li>
      </ul>
   </div>
   <h3>How objects spend their time<a name="1"></a></h3>
   <p>Let&#8217;s start with some basics &#8211; some of the places where objects spend time and how to minimize it.  Objects will spend time
      in four basic places &#8211; object construction, property access, method invocation, and object deletion.
   </p>
   <h3>Object Construction<a name="2"></a></h3>
   <p>Object construction time is mostly spent copying the default values of properties from the class definition to the object
      and then calling the object&#8217;s constructor function(s).  Generally speaking, there isn&#8217;t much to consider about default values
      in terms of performance since the expressions that create the default values are executed once when the class is first used,
      but then each object is just given a copy of the values from the class.  Generally more superclasses will mean more constructor
      function calls for each object creation so this is a factor to consider in performance critical code.
   </p>
   <h3>Property Access<a name="3"></a></h3>
   <p>Property access is one of the most important factors in object performance.  While changes over the past several releases
      have made property performance in R2012a more uniform and closer to struct performance, there is still some additional overhead
      for properties and the potential for aliasing with handle objects means that handle objects don&#8217;t get the same level of optimization
      that structs and value objects get from the MATLAB JIT.  The simpler a property can be, the faster it will be.  For example,
      making a property observable by listeners (using SetObservable/GetObservable) will turn off many optimizations and make property
      access slower.  Using a set or get function will turn off most optimizations and also introduce the extra time to call the
      set or get function which is generally much greater than the time to just access the property.  MATLAB doesn&#8217;t currently inline
      functions including set/get functions and so these are always executed as function calls.  MATLAB optimizes property reading
      separately from property writing so it is important not to add a get-function just because the property needs a set-function.
   </p>
   <p>Consider the following class:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">SimpleCylinder</span></pre><pre style="font-style:oblique">
classdef SimpleCylinder
    properties
        R
        Height 
    end
    
    methods
        function V = volume(C)
            V = pi .* [C.R].^2 .* [C.Height];
        end
    end
end
</pre><p>We can measure the time to create 1000 cylinders and compute their volumes:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">tic
C1 = SimpleCylinder;
<span style="color: #0000FF">for</span> k = 1:1000,
    C1(k).R = 1;
    C1(k).Height = k;
<span style="color: #0000FF">end</span>
V = volume(C1);
toc</pre><pre style="font-style:oblique">Elapsed time is 0.112309 seconds.
</pre><p>Now consider a slightly different version of the above class where the class checks all the property values:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">SlowCylinder</span></pre><pre style="font-style:oblique">
classdef SlowCylinder
    properties
        R
        Height
    end
    methods
        function V = volume(C)
            V = pi .* [C.R].^2 .* [C.Height];
        end
        
        function C = set.R(C, R)
            checkValue(R);
            C.R = R;
        end
        
        function C = set.Height(C, Height)
            checkValue(Height);
            C.Height = Height;
        end
    end
end

function checkValue(x)
    if ~isa(x, 'double') || ~isscalar(x)
        error('value must be a scalar double.');
    end
end


</pre><p>We can measure the same operations on this class:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">tic
C2 = SlowCylinder;
<span style="color: #0000FF">for</span> k = 1:1000,
    C2(k).R = 1;
    C2(k).Height = k;
<span style="color: #0000FF">end</span>
A = volume(C2);
toc</pre><pre style="font-style:oblique">Elapsed time is 0.174094 seconds.
</pre><h3>Optimizing for Property Usage Inside the Class<a name="8"></a></h3>
   <p>If much of the performance critical code is inside methods of the class, it might make sense to consider using two property
      definitions for properties accessed in such performance critical code.  One property is private to the class and doesn&#8217;t define
      any set or get functions.  A second dependent property is public and passes through to the private property but adds error
      checking in its set-function.  This allows the class to check values coming from outside the class, but not check values inside
      the class.  Set functions always execute except when setting the default value during object creation and this allows the
      class to use its public interface if it is more convenient to do so.  Set functions may do convenient transformations or other
      work in addition to just checking that the input value is legal for the property.  However, if a performance-critical method
      doesn&#8217;t need this work, it can be helpful to use two properties.
   </p>
   <p>For example, consider a new version of the cylinder class that checks its inputs but is designed to keep loops inside the
      class methods and use unchecked properties inside those methods.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">NewCylinder</span></pre><pre style="font-style:oblique">
classdef NewCylinder
    properties(Dependent)
        R
        Height
    end
    properties(Access=private)
        R_
        Height_
    end
    methods
        function C = NewCylinder(R, Height)
            if nargin &gt; 0
                if ~isa(R, 'double') || ~isa(Height, 'double')
                    error('R and Height must be double.');
                end
                
                if ~isequal(size(R), size(Height))
                    error('Dimensions of R and Height must match.');
                end
                for k = numel(R):-1:1
                    C(k).R_ = R(k);
                    C(k).Height_ = Height(k);
                end
            end            
        end
        
        function V = volume(C)
            V = pi .* [C.R_].^2 .* [C.Height_];
        end
        
        function C = set.R(C, R)
            checkValue(R);
            C.R_ = R;
        end

        function R = get.R(C)
            R = C.R_;
        end
        
        function C = set.Height(C, Height)
            checkValue(Height);
            C.Height_ = Height;
        end
        
        function Height = get.Height(C)
            Height = C.Height_;
        end        
    end
end

function checkValue(x)
    if ~isa(x, 'double') || ~isscalar(x)
        error('value must be a scalar double.');
    end
end


</pre><p>Here we measure the same operations as above.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">tic
C3 = NewCylinder(ones(1,1000), 1:1000);
A = volume(C3);
toc</pre><pre style="font-style:oblique">Elapsed time is 0.006654 seconds.
</pre><h3>Method Invocation<a name="11"></a></h3>
   <p>Method invocation using function call notation e.g. f(obj, data) is generally faster than using obj.f(data).  Method invocation,
      like function calls on structs, cells, and function handles will not benefit from JIT optimization of the function call and
      can be many times slower than function calls on purely numeric arguments. Because of the overhead for calling a method, it
      is always better to have a loop inside of a method rather than outside of a method.  Inside the method, if there is a loop,
      it will be faster if the loop just does indexing operations on the object and makes calls to functions that are passed numbers
      and strings from the object rather than method or function calls that take the whole object.  If function calls on the object
      can be factored outside of loops, that will generally improve performance.
   </p>
   <p>Calling a method on an object:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">C4 = NewCylinder(10, 20);
tic
<span style="color: #0000FF">for</span> k = 1:1000
    volume(C4);
<span style="color: #0000FF">end</span>
toc</pre><pre style="font-style:oblique">Elapsed time is 0.013509 seconds.
</pre><p>Calling a method on the object vector:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">C5 = NewCylinder(ones(1,1000), 1:1000);
tic
volume(C5);
toc</pre><pre style="font-style:oblique">Elapsed time is 0.001903 seconds.
</pre><p>Calling a function on a similar struct and struct array First calling the function inside a loop:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">CS1 = struct(<span style="color: #A020F0">'R'</span>, 10, <span style="color: #A020F0">'Height'</span>, 20);
tic
<span style="color: #0000FF">for</span> k = 1:1000
    cylinderVolume(CS1);
<span style="color: #0000FF">end</span></pre><p>Next, we call the function on a struct array:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">toc
CS2 = struct(<span style="color: #A020F0">'R'</span>, num2cell(ones(1,1000)), <span style="color: #0000FF">...</span>
             <span style="color: #A020F0">'Height'</span>, num2cell(1:1000));
tic
cylinderVolume(CS2);
toc</pre><pre style="font-style:oblique">Elapsed time is 0.008510 seconds.
Elapsed time is 0.000705 seconds.
</pre><h3>Deleting Handle Objects<a name="16"></a></h3>
   <p>MATLAB automatically deletes handle objects when they are no longer in use.  MATLAB doesn't use garbage collection to clean
      up objects periodically but instead destroys objects when they first become unreachable by any program.  This means that MATLAB
      destructors (the delete method) are called more deterministically than in environments using garbage collection, but it also
      means that MATLAB has to do more work whenever a program potentially changes the reachability of a handle object.  For example,
      when a variable that contains a handle goes out of scope, MATLAB has to determine whether or not that was the last reference
      to that variable.  This is not as simple as checking a reference count since MATLAB has to account for cycles of objects.
       Changes in R2011b and R2012a have made this process much faster and more uniform.  However, there is one aspect of object
      destruction that we are still working on and that has to do with recursive destruction.  As of R2012a, if a MATLAB object
      is destroyed, any handle objects referenced by its properties will also be destroyed if no longer reachable and this can in
      turn lead to destroying objects in properties of those objects and so on.  This can lead to very deep recursion for something
      like a very long linked list. Too much recursion can cause MATLAB to run out of system stack space and crash.  To avoid such
      an issue, you can explicitly destroy elements in a list rather than letting MATLAB discover that the whole list can be destroyed.
   </p>
   <p>Consider a doubly linked list of nodes using this node class:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">dlnode</span></pre><pre style="font-style:oblique">
classdef dlnode &lt; handle
    properties
        Data
    end
    properties(SetAccess = private)
        Next
        Prev
    end
    
    methods
        function node = dlnode(Data)
            node.Data = Data;
        end

        function delete(node)
            disconnect(node);
        end

        function disconnect(node)
            prev = node.Prev;
            next = node.Next;
            if ~isempty(prev)
                prev.Next = next;
            end
            if ~isempty(next)
                next.Prev = prev;
            end
            node.Next = [];
            node.Prev = [];
        end
        
        function insertAfter(newNode, nodeBefore)
            disconnect(newNode);
            newNode.Next = nodeBefore.Next;
            newNode.Prev = nodeBefore;
            if ~isempty(nodeBefore.Next)
                nodeBefore.Next.Prev = newNode;
            end
            nodeBefore.Next = newNode;
        end
        
        function insertBefore(newNode, nodeAfter)
            disconnect(newNode);
            newNode.Next = nodeAfter;
            newNode.Prev = nodeAfter.Prev;
            if ~isempty(nodeAfter.Prev)
                nodeAfter.Prev.Next = newNode;
            end
            nodeAfter.Prev = newNode;
        end       
    end
end

    
    
</pre><p>Create a list of 1000 elements:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">top = dlnode(0);
tic
<span style="color: #0000FF">for</span> i = 1:1000
    insertBefore(dlnode(i), top);
    top = top.Prev;
<span style="color: #0000FF">end</span>
toc</pre><pre style="font-style:oblique">Elapsed time is 0.123879 seconds.
</pre><p>Destroy the list explicitly to avoid exhausting the system stack:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">tic
<span style="color: #0000FF">while</span> ~isempty(top)
    oldTop = top;
    top = top.Next;
    disconnect(oldTop);
<span style="color: #0000FF">end</span>
toc</pre><pre style="font-style:oblique">Elapsed time is 0.113519 seconds.
</pre><p>Measure time for varying lengths of lists.  We expect to see time vary linearly with the number of nodes.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">N = [500 2000 5000 10000];
<span style="color: #228B22">% Create a list of 10000 elements:</span>
CreateTime = [];
TearDownTime = [];
<span style="color: #0000FF">for</span> n = N
    top = dlnode(0);
    tic
    <span style="color: #0000FF">for</span> i = 1:n
        insertBefore(dlnode(i), top);
        top = top.Prev;
    <span style="color: #0000FF">end</span>
    CreateTime = [CreateTime;toc];
    tic
    <span style="color: #0000FF">while</span> ~isempty(top)
        oldTop = top;
        top = top.Next;
        disconnect(oldTop);
    <span style="color: #0000FF">end</span>
    TearDownTime = [TearDownTime; toc];
<span style="color: #0000FF">end</span>
subplot(2,1,1);
plot(N, CreateTime);
title(<span style="color: #A020F0">'List Creation Time vs. List Length'</span>);
subplot(2,1,2);
plot(N, TearDownTime);
title(<span style="color: #A020F0">'List Destruction Time vs. List Length'</span>);</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/391/perfblog_01.png"> <h3>A Look to the Future<a name="21"></a></h3>
   <p>We continue to look for opportunities to improve MATLAB object performance and examples from you are very helpful for learning
      what changes will make an impact on real applications.  If you have examples or scenarios you want us to look at, please let
      me know.  Also, if you have your own ideas or best practices, it would be great to share them as well.  You can post ideas
      and comments <a href="http://blogs.mathworks.com/loren/?p=391#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_471974636ab641d99111e69b6397329c() {
        // 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='471974636ab641d99111e69b6397329c ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 471974636ab641d99111e69b6397329c';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

        author = 'Dave Foti';
        copyright = 'Copyright 2012 The MathWorks, Inc.';

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_471974636ab641d99111e69b6397329c()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.14<br /></p>
</div>
<!--
471974636ab641d99111e69b6397329c ##### SOURCE BEGIN #####
%% Considering Performance in Object-Oriented MATLAB Code
% Iâ€™m pleased to have Dave Foti back for a look at objects and performance.
% Dave manages the group responsible for object-oriented programming
% features in MATLAB.
%
% I often get questions along the lines of what performance penalty is paid
% for using objects or how fast will an object-oriented implementation
% perform compared with some other implementation.  As with many
% performance questions, the answer is that it very much depends on what
% the program is trying to do and what parts of its work are most
% performance-intensive.  I see many cases where most of the real work is
% inside methods of an object that do math on ordinary matrices.  Such
% applications wonâ€™t really see much difference with or without objects.  I
% also realize that many MATLAB users arenâ€™t nearly as concerned with
% run-time performance as with how long it takes to write the program.
% However, for those applications where performance matters and objects
% might be used in performance critical parts of the application, letâ€™s
% look at what can we say about how MATLAB works that might be helpful to
% consider.  Weâ€™ll also look at what has changed in recent MATLAB versions.

%% How objects spend their time
% Letâ€™s start with some basics â€“ some of the places where objects spend
% time and how to minimize it.  Objects will spend time in four basic
% places â€“ object construction, property access, method invocation, and
% object deletion.  

%% Object Construction
% Object construction time is mostly spent copying the default values of
% properties from the class definition to the object and then calling the
% objectâ€™s constructor function(s).  Generally speaking, there isnâ€™t much
% to consider about default values in terms of performance since the
% expressions that create the default values are executed once when the
% class is first used, but then each object is just given a copy of the
% values from the class.  Generally more superclasses will mean more
% constructor function calls for each object creation so this is a factor
% to consider in performance critical code.

%% Property Access
% Property access is one of the most important factors in object
% performance.  While changes over the past several releases have made
% property performance in R2012a more uniform and closer to struct
% performance, there is still some additional overhead for properties and
% the potential for aliasing with handle objects means that handle objects
% donâ€™t get the same level of optimization that structs and value objects
% get from the MATLAB JIT.  The simpler a property can be, the faster it
% will be.  For example, making a property observable by listeners (using
% SetObservable/GetObservable) will turn off many optimizations and make
% property access slower.  Using a set or get function will turn off most
% optimizations and also introduce the extra time to call the set or get
% function which is generally much greater than the time to just access the
% property.  MATLAB doesnâ€™t currently inline functions including set/get
% functions and so these are always executed as function calls.  MATLAB
% optimizes property reading separately from property writing so it is
% important not to add a get-function just because the property needs a
% set-function.
%
% Consider the following class:
%%
type SimpleCylinder
%%
% We can measure the time to create 1000 cylinders and compute their
% volumes:
tic
C1 = SimpleCylinder;
for k = 1:1000,
    C1(k).R = 1;
    C1(k).Height = k;
end
V = volume(C1);
toc
%%
% Now consider a slightly different version of the above class where the
% class checks all the property values:
type SlowCylinder
%%
% We can measure the same operations on this class:
tic
C2 = SlowCylinder;
for k = 1:1000,
    C2(k).R = 1;
    C2(k).Height = k;
end
A = volume(C2);
toc

%% Optimizing for Property Usage Inside the Class
% If much of the performance critical code is inside methods of the class,
% it might make sense to consider using two property definitions for
% properties accessed in such performance critical code.  One property is
% private to the class and doesnâ€™t define any set or get functions.  A
% second dependent property is public and passes through to the private
% property but adds error checking in its set-function.  This allows the
% class to check values coming from outside the class, but not check values
% inside the class.  Set functions always execute except when setting the
% default value during object creation and this allows the class to use its
% public interface if it is more convenient to do so.  Set functions may do
% convenient transformations or other work in addition to just checking
% that the input value is legal for the property.  However, if a
% performance-critical method doesnâ€™t need this work, it can be helpful to
% use two properties.
%%
% For example, consider a new version of the cylinder class that checks its
% inputs but is designed to keep loops inside the class methods and use 
% unchecked properties inside those methods.
type NewCylinder
%%
% Here we measure the same operations as above. 
tic
C3 = NewCylinder(ones(1,1000), 1:1000);
A = volume(C3);
toc

%% Method Invocation
% Method invocation using function call notation e.g. f(obj, data) is
% generally faster than using obj.f(data).  Method invocation, like
% function calls on structs, cells, and function handles will not benefit
% from JIT optimization of the function call and can be many times slower
% than function calls on purely numeric arguments. Because of the overhead
% for calling a method, it is always better to have a loop inside of a
% method rather than outside of a method.  Inside the method, if there is a
% loop, it will be faster if the loop just does indexing operations on the
% object and makes calls to functions that are passed numbers and strings
% from the object rather than method or function calls that take the whole
% object.  If function calls on the object can be factored outside of
% loops, that will generally improve performance.
%%
% Calling a method on an object:
C4 = NewCylinder(10, 20);
tic
for k = 1:1000
    volume(C4);
end
toc
%%
% Calling a method on the object vector:
C5 = NewCylinder(ones(1,1000), 1:1000);
tic
volume(C5);
toc
%%
% Calling a function on a similar struct and struct array
% First calling the function inside a loop:
CS1 = struct('R', 10, 'Height', 20);
tic
for k = 1:1000
    cylinderVolume(CS1);
end
%%
% Next, we call the function on a struct array:
toc
CS2 = struct('R', num2cell(ones(1,1000)), ... 
             'Height', num2cell(1:1000));
tic
cylinderVolume(CS2);
toc


%% Deleting Handle Objects
% MATLAB automatically deletes handle objects when they are no longer in
% use.  MATLAB doesn't use garbage collection to clean up objects
% periodically but instead destroys objects when they first become
% unreachable by any program.  This means that MATLAB destructors (the
% delete method) are called more deterministically than in environments
% using garbage collection, but it also means that MATLAB has to do more
% work whenever a program potentially changes the reachability of a handle
% object.  For example, when a variable that contains a handle goes out of
% scope, MATLAB has to determine whether or not that was the last reference
% to that variable.  This is not as simple as checking a reference count
% since MATLAB has to account for cycles of objects.  Changes in R2011b and
% R2012a have made this process much faster and more uniform.  However,
% there is one aspect of object destruction that we are still working on
% and that has to do with recursive destruction.  As of R2012a, if a MATLAB
% object is destroyed, any handle objects referenced by its properties will
% also be destroyed if no longer reachable and this can in turn lead to
% destroying objects in properties of those objects and so on.  This can
% lead to very deep recursion for something like a very long linked list.
% Too much recursion can cause MATLAB to run out of system stack space and
% crash.  To avoid such an issue, you can explicitly destroy elements in a
% list rather than letting MATLAB discover that the whole list can be
% destroyed.
%%
% Consider a doubly linked list of nodes using this node class:
type dlnode
%%
% Create a list of 1000 elements:
top = dlnode(0);
tic
for i = 1:1000
    insertBefore(dlnode(i), top);
    top = top.Prev;
end
toc
%%
% Destroy the list explicitly to avoid exhausting the system stack:
tic
while ~isempty(top)
    oldTop = top;
    top = top.Next;
    disconnect(oldTop);
end
toc
%%
% Measure time for varying lengths of lists.  We expect to see time vary
% linearly with the number of nodes. 
N = [500 2000 5000 10000];
% Create a list of 10000 elements:
CreateTime = [];  
TearDownTime = [];
for n = N
    top = dlnode(0);
    tic
    for i = 1:n
        insertBefore(dlnode(i), top);
        top = top.Prev;
    end
    CreateTime = [CreateTime;toc];
    tic
    while ~isempty(top)
        oldTop = top;
        top = top.Next;
        disconnect(oldTop);
    end
    TearDownTime = [TearDownTime; toc];
end
subplot(2,1,1);
plot(N, CreateTime);
title('List Creation Time vs. List Length');
subplot(2,1,2);
plot(N, TearDownTime);
title('List Destruction Time vs. List Length');

%% A Look to the Future
% We continue to look for opportunities to improve MATLAB object
% performance and examples from you are very helpful for learning what
% changes will make an impact on real applications.  If you have examples
% or scenarios you want us to look at, please let me know.  Also, if you
% have your own ideas or best practices, it would be great to share them as
% well.  You can post ideas and comments
% <http://blogs.mathworks.com/loren/?p=391#respond here>.




##### SOURCE END ##### 471974636ab641d99111e69b6397329c
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/REziEzN7JwY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/03/26/considering-performance-in-object-oriented-matlab-code/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/03/26/considering-performance-in-object-oriented-matlab-code/</feedburner:origLink></item>
		<item>
		<title>New Regression Capabilities in Release 2012A</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/liUmfPaQK6Y/</link>
		<comments>http://blogs.mathworks.com/loren/2012/03/16/new-regression-capabilities-in-release-2012a/#comments</comments>
		<pubDate>Fri, 16 Mar 2012 19:14:29 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Curve fitting]]></category>
		<category><![CDATA[Statistics]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=385</guid>
		<description><![CDATA[This week Richard Willey from technical marketing will be guest blogging about new regression capabilities shipping with the 12a Statistics Toolbox release. Contents Create a dataset Use linear regression to model Y as a function of X Use myFit for analysis Look for patterns in the residuals Look for autocorrelation in the residuals Look for [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p><i>This week Richard Willey from technical marketing will be guest blogging about new regression capabilities shipping with the
            12a <a href="http://www.mathworks.com/products/statistics/">Statistics Toolbox</a> release.</i></p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#2">Create a dataset</a></li>
         <li><a href="#3">Use linear regression to model Y as a function of X</a></li>
         <li><a href="#5">Use myFit for analysis</a></li>
         <li><a href="#7">Look for patterns in the residuals</a></li>
         <li><a href="#9">Look for autocorrelation in the residuals</a></li>
         <li><a href="#10">Look for outliers</a></li>
         <li><a href="#12">Use the resulting model for prediction</a></li>
         <li><a href="#13">Discover the full set of methods available with regression objects</a></li>
         <li><a href="#14">Discover the full set of information included in the regression object</a></li>
         <li><a href="#15">Formulas</a></li>
         <li><a href="#17">Modeling a high order polynomial (Option 1)</a></li>
         <li><a href="#18">Modeling a high order polynomial (Option 2)</a></li>
         <li><a href="#19">Nonlinear regression:  Generate our data</a></li>
         <li><a href="#20">Nonlinear regression:  Generate a fit</a></li>
         <li><a href="#21">Nonlinear regression: Work with the resulting model</a></li>
         <li><a href="#22">Nonlinear regression:  Alternative ways to specify the regression model</a></li>
         <li><a href="#23">Conclusion</a></li>
      </ul>
   </div>
   <p>The 12a release of Statistics Toolbox includes new functions for</p>
   <div>
      <ul>
         <li>Linear regression</li>
         <li>Nonlinear regression</li>
         <li>Logistic regression (and other types of generalized linear models)</li>
      </ul>
   </div>
   <p>These regression techniques aren&#8217;t new to Statistics Toolbox.  What is new is that MathWorks addded a wide set of support
      functions that simplify common analysis tasks like plotting, outlier detection, generating predictions, performing stepwise
      regression, applying robust regression...
   </p>
   <p>We'll start with a simple example using linear regression.</p>
   <h3>Create a dataset<a name="2"></a></h3>
   <p>I'm going to generate a basic dataset in which the relationship between X and Y is modeled by a straight line (Y = mX + B)
      and add in some normally distributed noise. Next, I'll generate a scatter plot showing the relationship between X and Y
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">clear <span style="color: #A020F0">all</span>
clc
rng(1998);

X = linspace(1,100,50);
X = X';
Y = 7*X + 50 + 30*randn(50,1);
New_X = 100 * rand(10,1);

scatter(X,Y, <span style="color: #A020F0">'.'</span>)</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/385/fit12a_01.png"> <h3>Use linear regression to model Y as a function of X<a name="3"></a></h3>
   <p>Looking at the data, we can see a clear linear relationship between X and Y.  I'm going to use the new LinearModel function
      to model Y as a function of X.  The output from this function will be stored as an object named "myFit" which is displayed
      on the screen.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">myFit = LinearModel.fit(X,Y)</pre><pre style="font-style:oblique">myFit = 
Linear regression model:
    y ~ 1 + x1

Estimated Coefficients:
                   Estimate    SE         tStat     pValue    
    (Intercept)      51.6       8.2404    6.2618    9.9714e-08
    x1             7.0154      0.14131    49.644    6.4611e-43

Number of observations: 50, Error degrees of freedom: 48
Root Mean Squared Error: 29.1
R-squared: 0.981,  Adjusted R-Squared 0.98
F-statistic vs. constant model: 2.46e+03, p-value = 6.46e-43
</pre><p>The first line shows the linear regression model.  When perform a regression we need to specify a model that describes the
      relationship between our variables.  By default, LinearModel assumes that you want to model the relationship as a straight
      line with an intercept term.  The expression "y ~ 1 + x1" describes this model.  Formally, this expression translates as "Y
      is modeled as a linear function which includes an intercept and a variable".  Once again note that we are representing a model
      of the form Y = mX + B...
   </p>
   <p>The next block of text includes estimates for the coefficients, along with basic information regarding the reliability of
      those estimates.
   </p>
   <p>Finally, we have basic information about the goodness-of-fit including the R-square, the adjusted R-square and the Root Mean
      Squared Error.
   </p>
   <h3>Use myFit for analysis<a name="5"></a></h3>
   <p>Earlier, I mentioned that the new regression functions include a wide variety of support functions that automate different
      analysis tasks. Let's look at some them.
   </p>
   <p>First, lets generate a plot that we can use to evaluate the quality of the resulting fit.  We'll do so by applying the standard
      MATLAB plot command to "myFit".
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">plot(myFit)</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/385/fit12a_02.png"> <p>Notice that this simple command creates a plot with a wealth of information including</p>
   <div>
      <ul>
         <li>A scatter plot of the original dataset</li>
         <li>A line showing our fit</li>
         <li>Confidence intervals for the fit</li>
      </ul>
   </div>
   <p>MATLAB has also automatically labelled our axes and added a legend.</p>
   <h3>Look for patterns in the residuals<a name="7"></a></h3>
   <p>Alternatively, lets assume that we wanted to see whether there was any pattern to the residuals.  (A noticeable pattern to
      the residuals might suggest that our model is to simple and that it failed to capture a real work trend in the data set. 
      This technique can also be used to check and see whether the noise component is constant across the dataset).
   </p>
   <p>Here, I'll pass "myFit" to the new "plotResiduals" method and tell plotResiduals to plot the residuals versus the fitted values.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">figure
plotResiduals(myFit, <span style="color: #A020F0">'fitted'</span>)</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/385/fit12a_03.png"> <p>My plot looks like random noise - which in this case is a very good thing.</p>
   <h3>Look for autocorrelation in the residuals<a name="9"></a></h3>
   <p>Autocorrelation in my data set could also throw off the quality of my fit.  The following command will modify the residual
      plot by plotting residuals versus lagged residuals.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">figure
plotResiduals(myFit, <span style="color: #A020F0">'lagged'</span>)</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/385/fit12a_04.png"> <h3>Look for outliers<a name="10"></a></h3>
   <p>Suppose that I wanted to check for outliers...  We also have a plot for that.</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">figure
plotDiagnostics(myFit, <span style="color: #A020F0">'cookd'</span>)</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/385/fit12a_05.png"> <p>Cook's Distance is a metric that is commonly used to see whether a dataset contains any outliers.  For any given data point,
      Cook's Distance is calculated by performing a brand new regression that excludes that data point.  Cook's distance measures
      how much the shape of the curve changes between the two fits.  If the curve moves by a large amount, that data point has a
      great deal of influence on the model and might very well be an outlier.
   </p>
   <div>
      <ul>
         <li>The red crosses show the Cook's Distance for each point in the data set.</li>
         <li>The horizontal line shows "Three times the average Cook's Distance for all the points in the data set".  Data points whose
            Cook's Distance is greater than three times the mean are often considered possible outliers.
         </li>
      </ul>
   </div>
   <p>In this example, non of our data points look as if they are outliers.</p>
   <h3>Use the resulting model for prediction<a name="12"></a></h3>
   <p>Last, but not least, lets assume that we wanted to use our model for prediction.  This is as easy as applying the "predict"
      method.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">Predictions = predict(myFit, New_X)</pre><pre style="font-style:oblique">Predictions =
       310.51
       596.17
       64.866
       490.79
       306.06
       308.87
       621.55
       366.15
       543.32
       317.33
</pre><h3>Discover the full set of methods available with regression objects<a name="13"></a></h3>
   <p>I hope that you agree that all these built in plots and analysis routines represent a significant improvement in usability.
       However, if you're anything like me, you immediate reaction is going to be "Great, you've built a lot of nice stuff, however,
      how do you expect me to find out about this?"
   </p>
   <p>What I'd like to do now is show you a couple of simple tricks that you can use to discover all the new cabilities that we've
      added.  The first trick is to recognize that "myFit" is an object and that objects have methods associated with them.  All
      of the commands that we've sued so far like "plot", "plotResiduals", and "predict" are methods for the LinearModel object.
   </p>
   <p>Any time that I'm working with one of the built in objects that ship with MATLAB my first plot is to inspect the full set
      of methods that ship with that object.  This is as easy as typing methods(myFit) at the command line.  I can use this to immediately
      discover all the built in capabilities that ship with the object. If one of those options catches my eye, I can use the help
      system to get more information.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">methods(myFit)</pre><pre style="font-style:oblique">
Methods for class LinearModel:

addTerms              plot                  plotSlice             
anova                 plotAdded             predict               
coefCI                plotAdjustedResponse  random                
coefTest              plotDiagnostics       removeTerms           
disp                  plotEffects           step                  
dwtest                plotInteraction       
feval                 plotResiduals         

Static methods:

fit                   stepwise              

</pre><h3>Discover the full set of information included in the regression object<a name="14"></a></h3>
   <p>Here's another really useful trick to learn about the new regression objects.  You can use the MATLAB variable editor to walk
      through the object and see all the information that is availabe.
   </p>
   <p>You should have an object named "myFit" in the MATLAB workspace.  Double clicking on the object will open the object in the
      Variable Editor.
   </p>
   <h3>Formulas<a name="15"></a></h3>
   <p>At the start of this blog there was some brief introduction to "formulas".  I'd like to conclude this talk by providing a
      bit more information about formulas.  Regression analysis requires the ability to specify a model that describes the relationship
      between your predictors and your response variables.
   </p>
   <p>Let's change our initial example such that we're working with a high order polynomial rather than a straight line.  I'm also
      going to change this from a curve fitting problem to a surface fitting problem.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">X1 = 100 * randn(100,1);
X2 = 100 * rand(100,1);
X = [X1, X2];
Y = 3*X1.^2 + 5*X1.*X2 + 7* X2.^2 + 9*X1 + 11*X2 + 30 + 100*randn(100,1);
myFit2 = LinearModel.fit(X,Y)</pre><pre style="font-style:oblique">myFit2 = 
Linear regression model:
    y ~ 1 + x1 + x2

Estimated Coefficients:
                   Estimate    SE       tStat     pValue   
    (Intercept)     25771      11230    2.2949     0.023893
    x1             178.75      54.95     3.253    0.0015717
    x2             613.39      187.2    3.2767    0.0014579

Number of observations: 100, Error degrees of freedom: 97
Root Mean Squared Error: 5.42e+04
R-squared: 0.211,  Adjusted R-Squared 0.195
F-statistic vs. constant model: 13, p-value = 1.03e-05
</pre><p>Let's take a look at the output from this example.  We can see, almost immediately, that something has gone wrong with our
      fit.
   </p>
   <div>
      <ul>
         <li>The R^2 value is pretty bad</li>
         <li>The regression coefficients are nowhere near the ones we specified when we created the dataset</li>
      </ul>
   </div>
   <p>If we look at the line that describes the linear regression model we can see what went wrong.  By default, LinearModel will
      fit a plane to the dataset.  Here, the relationship between X and Y is modelled as a high order polynomial.  We need to pass
      this additional piece of information to "LinearModel".
   </p>
   <h3>Modeling a high order polynomial (Option 1)<a name="17"></a></h3>
   <p>Here are a couple different ways that I can use LinearModel to model a high order polynomial.  The first option is to write
      out the formula by hand.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">myFit2 = LinearModel.fit(X,Y, <span style="color: #A020F0">'y ~ 1 + x1^2 + x2^2 + x1:x2 + x1 + x2'</span>)</pre><pre style="font-style:oblique">myFit2 = 
Linear regression model:
    y ~ 1 + x1*x2 + x1^2 + x2^2

Estimated Coefficients:
                   Estimate    SE           tStat      pValue     
    (Intercept)    32.317         38.071    0.84886        0.39811
    x1             9.1735         0.2119     43.291     6.9346e-64
    x2              12.19         1.6568     7.3577     6.9388e-11
    x1:x2          4.9985      0.0033943     1472.6    7.0691e-207
    x1^2           2.9992      0.0006268       4785    5.5265e-255
    x2^2           6.9849       0.015281     457.11    3.9814e-159

Number of observations: 100, Error degrees of freedom: 94
Root Mean Squared Error: 101
R-squared: 1,  Adjusted R-Squared 1
F-statistic vs. constant model: 7.02e+06, p-value = 3.23e-260
</pre><h3>Modeling a high order polynomial (Option 2)<a name="18"></a></h3>
   <p>Alternatively, I can simple use the the string "poly22" to indicate a second order polynomial for both X1 and X2 an automatically
      generate all the appropriate terms and cross terms.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">myFit2 = LinearModel.fit(X, Y, <span style="color: #A020F0">'poly22'</span>)</pre><pre style="font-style:oblique">myFit2 = 
Linear regression model:
    y ~ 1 + x1^2 + x1*x2 + x2^2

Estimated Coefficients:
                   Estimate    SE           tStat      pValue     
    (Intercept)    32.317         38.071    0.84886        0.39811
    x1             9.1735         0.2119     43.291     6.9346e-64
    x2              12.19         1.6568     7.3577     6.9388e-11
    x1^2           2.9992      0.0006268       4785    5.5265e-255
    x1:x2          4.9985      0.0033943     1472.6    7.0691e-207
    x2^2           6.9849       0.015281     457.11    3.9814e-159

Number of observations: 100, Error degrees of freedom: 94
Root Mean Squared Error: 101
R-squared: 1,  Adjusted R-Squared 1
F-statistic vs. constant model: 7.02e+06, p-value = 3.23e-260
</pre><h3>Nonlinear regression:  Generate our data<a name="19"></a></h3>
   <p>Let's consider a nonlinear regression example.  This time around, we'll work with a sin curve.  The equation for a sin curve
      is governed by four key parameters.
   </p>
   <div>
      <ol>
         <li>The phase</li>
         <li>The amplitude</li>
         <li>The vertical shift</li>
         <li>The phase shift</li>
      </ol>
   </div>
   <p>We'll start by generating a our dataset</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">X = linspace(0, 6*pi, 90);
X = X';
Y = 10 + 3*(sin(1*X + 5)) + .2*randn(90,1);</pre><h3>Nonlinear regression:  Generate a fit<a name="20"></a></h3>
   <p>Next we'll using the NonLinearModel function to perform a nonlinear regression.  Here we need to</p>
   <div>
      <ol>
         <li>Specify formula that describes the relationship between X and Y</li>
         <li>Provide some reasonable starting conditions for the optimization solvers</li>
      </ol>
   </div><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">myFit3 = NonLinearModel.fit(X,Y, <span style="color: #A020F0">'y ~ b0 + b1*sin(b2*x + b3)'</span>, [11, 2.5, 1.1, 5.5])</pre><pre style="font-style:oblique">myFit3 = 
Nonlinear regression model:
    y ~ b0 + b1*sin(b2*x + b3)

Estimated Coefficients:
          Estimate    SE           tStat     pValue     
    b0     9.9751       0.02469    404.02    9.0543e-143
    b1     2.9629      0.033784    87.703     6.4929e-86
    b2    0.99787     0.0021908    455.47     3.029e-147
    b3     5.0141      0.023119    216.88    1.4749e-119

Number of observations: 90, Error degrees of freedom: 86
Root Mean Squared Error: 0.227
R-Squared: 0.989,  Adjusted R-Squared 0.989
F-statistic vs. constant model: 2.58e+03, p-value = 4.36e-84
</pre><h3>Nonlinear regression: Work with the resulting model<a name="21"></a></h3>
   <p>Once again, the output from the regression analysis is an object which we can used for analysis.  For example:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">figure
scatter(X,Y)
hold <span style="color: #A020F0">on</span>
plot(X, myFit3.Fitted, <span style="color: #A020F0">'r'</span>)</pre><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/385/fit12a_06.png"> <h3>Nonlinear regression:  Alternative ways to specify the regression model<a name="22"></a></h3>
   <p>One last point to be aware of:  The syntax that I have been using to specify regression models is based on "Wilkinson's notation".
       This is a standard syntax that is commonly used in Statistics.  If you prefer, you also have the option to specify your model
      using anonymous functions.
   </p>
   <p>For example, that command could have been written as</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">myFit4 = NonLinearModel.fit(X,Y, @(b,x)(b(1) + b(2)*sin(b(3)*x + b(4))), [11, 2.5, 1.1, 5.5])</pre><pre style="font-style:oblique">myFit4 = 
Nonlinear regression model:
    y ~ (b1 + b2*sin(b3*x + b4))

Estimated Coefficients:
          Estimate    SE           tStat     pValue     
    b1     9.9751       0.02469    404.02    9.0543e-143
    b2     2.9629      0.033784    87.703     6.4929e-86
    b3    0.99787     0.0021908    455.47     3.029e-147
    b4     5.0141      0.023119    216.88    1.4749e-119

Number of observations: 90, Error degrees of freedom: 86
Root Mean Squared Error: 0.227
R-Squared: 0.989,  Adjusted R-Squared 0.989
F-statistic vs. constant model: 2.58e+03, p-value = 4.36e-84
</pre><h3>Conclusion<a name="23"></a></h3>
   <p>I've been working with Statistics Toolbox for close to five years now. Other than the introduction of dataset arrays a few
      years back, nothing has gotten me nearly as excited as the release of these new regression capabilities.  So, it seemed fitting
      to conclude with an example that combines dataset arrays and the new regression objects.
   </p>
   <p>Tell me what you think is going on in the following example.  (Extra credit if you can work in the expression "dummy variable")</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">load <span style="color: #A020F0">carsmall</span>

ds = dataset(MPG,Weight);
ds.Year = ordinal(Model_Year);

mdl = LinearModel.fit(ds,<span style="color: #A020F0">'MPG ~ Year + Weight^2'</span>)</pre><pre style="font-style:oblique">mdl = 
Linear regression model:
    MPG ~ 1 + Weight + Year + Weight^2

Estimated Coefficients:
                   Estimate      SE            tStat      pValue    
    (Intercept)        54.206        4.7117     11.505    2.6648e-19
    Weight          -0.016404     0.0031249    -5.2493    1.0283e-06
    Year_76            2.0887       0.71491     2.9215     0.0044137
    Year_82            8.1864       0.81531     10.041    2.6364e-16
    Weight^2       1.5573e-06    4.9454e-07      3.149     0.0022303

Number of observations: 94, Error degrees of freedom: 89
Root Mean Squared Error: 2.78
R-squared: 0.885,  Adjusted R-Squared 0.88
F-statistic vs. constant model: 172, p-value = 5.52e-41
</pre><p>Post your answers <a href="http://blogs.mathworks.com/loren/?p=385#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_3fa6aab696514fcb80b3158f689b4e51() {
        // 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='3fa6aab696514fcb80b3158f689b4e51 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 3fa6aab696514fcb80b3158f689b4e51';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

        author = 'Richard Willey';
        copyright = 'Copyright 2012 The MathWorks, Inc.';

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_3fa6aab696514fcb80b3158f689b4e51()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.14<br /></p>
</div>
<!--
3fa6aab696514fcb80b3158f689b4e51 ##### SOURCE BEGIN #####
%% New Regression Capabilities in Release 2012A
% _This week Richard Willey from technical marketing will be guest blogging
% about new regression capabilities shipping with the 12a <http://www.mathworks.com/products/statistics/ Statistics Toolbox> release._
 


%%
% The 12a release of Statistics Toolbox includes new functions for 
%
% * Linear regression
% * Nonlinear regression 
% * Logistic regression (and other types of generalized linear models)
%
% These regression techniques arenâ€™t new to Statistics Toolbox.  What is
% new is that MathWorks addded a wide set of support functions that 
% simplify common analysis tasks like plotting, outlier detection, 
% generating predictions, performing stepwise regression, applying robust 
% regression...
%
% We'll start with a simple example using linear regression.
 
 
%% Create a dataset
%
% I'm going to generate a basic dataset in which the relationship between X
% and Y is modeled by a straight line (Y = mX + B) and add in some normally 
% distributed noise. Next, I'll generate a scatter plot showing the 
% relationship between X and Y
 
clear all
clc
rng(1998);
 
X = linspace(1,100,50);
X = X';
Y = 7*X + 50 + 30*randn(50,1);
New_X = 100 * rand(10,1);
 
scatter(X,Y, '.')
 
%% Use linear regression to model Y as a function of X
%
% Looking at the data, we can see a clear linear relationship between X 
% and Y.  I'm going to use the new LinearModel function to model
% Y as a function of X.  The output from this function will be stored as an
% object named "myFit" which is displayed on the screen.
 
myFit = LinearModel.fit(X,Y)

%%
% The first line shows the linear regression model.  When perform a
% regression we need to specify a model that describes the relationship
% between our variables.  By default, LinearModel assumes that you want to
% model the relationship as a straight line with an intercept term.  The
% expression "y ~ 1 + x1" describes this model.  Formally, this expression 
% translates as "Y is modeled as a linear function which includes an 
% intercept and a variable".  Once again note that we are representing a 
% model of the form Y = mX + B...
%
% The next block of text includes estimates for the coefficients, along
% with basic information regarding the reliability of those estimates.  
%
% Finally, we have basic information about the goodness-of-fit including
% the R-square, the adjusted R-square and the Root Mean Squared Error.
 
%% Use myFit for analysis
%
% Earlier, I mentioned that the new regression functions include a wide
% variety of support functions that automate different analysis tasks.
% Let's look at some them.
%
% First, lets generate a plot that we can use to evaluate the quality of
% the resulting fit.  We'll do so by applying the standard MATLAB plot
% command to "myFit".
 
plot(myFit)

%%
% Notice that this simple command creates a plot with a wealth of
% information including
%
% * A scatter plot of the original dataset
% * A line showing our fit
% * Confidence intervals for the fit
%
% MATLAB has also automatically labelled our axes and added a legend.
 
%% Look for patterns in the residuals
%
% Alternatively, lets assume that we wanted to see whether there was any
% pattern to the residuals.  (A noticeable pattern to the residuals might
% suggest that our model is to simple and that it failed to capture a real
% work trend in the data set.  This technique can also be used to check and
% see whether the noise component is constant across the dataset).  
%
% Here, I'll pass "myFit" to the new "plotResiduals" method and tell
% plotResiduals to plot the residuals versus the fitted values.
 
figure
plotResiduals(myFit, 'fitted') 

%%
% My plot looks like random noise - which in this case is a very good
% thing.  
 
%% Look for autocorrelation in the residuals
%
% Autocorrelation in my data set could also throw off the quality 
% of my fit.  The following command will modify the residual plot by 
% plotting residuals versus lagged residuals.
 
figure
plotResiduals(myFit, 'lagged')
 
%% Look for outliers
%
% Suppose that I wanted to check for outliers...  We also have a plot for
% that.
 
figure
plotDiagnostics(myFit, 'cookd')

%%
% Cook's Distance is a metric that is commonly used to see whether a
% dataset contains any outliers.  For any given data point, Cook's Distance
% is calculated by performing a brand new regression that excludes that
% data point.  Cook's distance measures how much the shape of the curve
% changes between the two fits.  If the curve moves by a large amount, that
% data point has a great deal of influence on the model and might very well
% be an outlier.  
%
% * The red crosses show the Cook's Distance for each point in the data set.  
% * The horizontal line shows "Three times the average Cook's Distance for
% all the points in the data set".  Data points whose Cook's Distance is 
% greater than three times the mean are often considered possible outliers.
%
% In this example, non of our data points look as if they are outliers. 
 
%% Use the resulting model for prediction
%
% Last, but not least, lets assume that we wanted to use our model for
% prediction.  This is as easy as applying the "predict" method.
 
Predictions = predict(myFit, New_X)
 
%% Discover the full set of methods available with regression objects
%
% I hope that you agree that all these built in plots and analysis routines
% represent a significant improvement in usability.  However, if you're
% anything like me, you immediate reaction is going to be "Great, you've
% built a lot of nice stuff, however, how do you expect me to find out
% about this?"
%
% What I'd like to do now is show you a couple of simple tricks that you
% can use to discover all the new cabilities that we've added.  The first
% trick is to recognize that "myFit" is an object and that objects have
% methods associated with them.  All of the commands that we've sued so far
% like "plot", "plotResiduals", and "predict" are methods for the
% LinearModel object.
%
% Any time that I'm working with one of the built in objects that ship with
% MATLAB my first plot is to inspect the full set of methods that ship with
% that object.  This is as easy as typing methods(myFit) at the command
% line.  I can use this to immediately discover all the built in 
% capabilities that ship with the object. If one of those options catches
% my eye, I can use the help system to get more information.
 
methods(myFit) 
 
%% Discover the full set of information included in the regression object
%
% Here's another really useful trick to learn about the new regression
% objects.  You can use the MATLAB variable editor to walk through the
% object and see all the information that is availabe.  
%
% You should have an object named "myFit" in the MATLAB workspace.  Double
% clicking on the object will open the object in the Variable Editor. 
 
%% Formulas
%
% At the start of this blog there was some brief introduction to
% "formulas".  I'd like to conclude this talk by providing a bit more
% information about formulas.  Regression analysis requires the ability to
% specify a model that describes the relationship between your predictors
% and your response variables.
%
% Let's change our initial example such that we're working with a high
% order polynomial rather than a straight line.  I'm also going to change
% this from a curve fitting problem to a surface fitting problem.
 
X1 = 100 * randn(100,1);
X2 = 100 * rand(100,1);
X = [X1, X2];
Y = 3*X1.^2 + 5*X1.*X2 + 7* X2.^2 + 9*X1 + 11*X2 + 30 + 100*randn(100,1); 
myFit2 = LinearModel.fit(X,Y)

%%
% Let's take a look at the output from this example.  We can see, almost
% immediately, that something has gone wrong with our fit.
%
% * The R^2 value is pretty bad
% * The regression coefficients are nowhere near the ones we specified when
% we created the dataset
%
% If we look at the line that describes the linear regression model we can 
% see what went wrong.  By default, LinearModel will fit a plane to the
% dataset.  Here, the relationship between X and Y is modelled as a high
% order polynomial.  We need to pass this additional piece of information 
% to "LinearModel".
 
%%  Modeling a high order polynomial (Option 1)
%
% Here are a couple different ways that I can use LinearModel to model a
% high order polynomial.  The first option is to write out the formula by
% hand.
 
myFit2 = LinearModel.fit(X,Y, 'y ~ 1 + x1^2 + x2^2 + x1:x2 + x1 + x2')
 
%% Modeling a high order polynomial (Option 2)
%
% Alternatively, I can simple use the the string "poly22" to indicate a
% second order polynomial for both X1 and X2 an automatically generate all
% the appropriate terms and cross terms.
 
myFit2 = LinearModel.fit(X, Y, 'poly22')
 
%% Nonlinear regression:  Generate our data
%
% Let's consider a nonlinear regression example.  This time around,
% we'll work with a sin curve.  The equation for a sin curve is governed by
% four key parameters.
%
% # The phase
% # The amplitude
% # The vertical shift
% # The phase shift
%
% We'll start by generating a our dataset
 
X = linspace(0, 6*pi, 90);
X = X';
Y = 10 + 3*(sin(1*X + 5)) + .2*randn(90,1);
 
%% Nonlinear regression:  Generate a fit
%
% Next we'll using the NonLinearModel function to perform a nonlinear
% regression.  Here we need to 
%
% # Specify formula that describes the relationship between X and Y
% # Provide some reasonable starting conditions for the optimization
% solvers
 
myFit3 = NonLinearModel.fit(X,Y, 'y ~ b0 + b1*sin(b2*x + b3)', [11, 2.5, 1.1, 5.5])
 
%% Nonlinear regression: Work with the resulting model
%
% Once again, the output from the regression analysis is an object which we
% can used for analysis.  For example:
%
 
figure
scatter(X,Y)
hold on
plot(X, myFit3.Fitted, 'r')
 
%% Nonlinear regression:  Alternative ways to specify the regression model
%
% One last point to be aware of:  The syntax that I have been using to
% specify regression models is based on "Wilkinson's notation".  This is a
% standard syntax that is commonly used in Statistics.  If you prefer, you
% also have the option to specify your model using anonymous functions.
%
% For example, that command could have been written as
 
myFit4 = NonLinearModel.fit(X,Y, @(b,x)(b(1) + b(2)*sin(b(3)*x + b(4))), [11, 2.5, 1.1, 5.5])
 
%% Conclusion
%
% I've been working with Statistics Toolbox for close to five years now.
% Other than the introduction of dataset arrays a few years back, nothing
% has gotten me nearly as excited as the release of these new regression
% capabilities.  So, it seemed fitting to conclude with an example that
% combines dataset arrays and the new regression objects.
%
% Tell me what you think is going on in the following example.  (Extra 
% credit if you can work in the expression "dummy variable")
% 
load carsmall
 
ds = dataset(MPG,Weight);
ds.Year = ordinal(Model_Year);
 
mdl = LinearModel.fit(ds,'MPG ~ Year + Weight^2')

%%
% Post your answers <http://blogs.mathworks.com/loren/?p=385#respond
% here>.






##### SOURCE END ##### 3fa6aab696514fcb80b3158f689b4e51
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/liUmfPaQK6Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/03/16/new-regression-capabilities-in-release-2012a/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/03/16/new-regression-capabilities-in-release-2012a/</feedburner:origLink></item>
		<item>
		<title>MATLAB Virtual Conference – 28 March 2012</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/ZrpaPHOaeSo/</link>
		<comments>http://blogs.mathworks.com/loren/2012/03/09/matlab-virtual-conference-28-march-2012/#comments</comments>
		<pubDate>Fri, 09 Mar 2012 18:27:52 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=376</guid>
		<description><![CDATA[I am pleased to announce that we have another MATLAB Virtual Conference planned and taking place towards the end of March 2012. I would like to formally invite you to join us on March 28, 2012. Contents Conference Information Brief Conference Agenda Join Us! Conference Information You'll find information about the conference here as well [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>I am pleased to announce that we have another MATLAB Virtual Conference planned and taking place towards the end of March
         2012.  I would like to formally invite you to join us on March 28, 2012.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Conference Information</a></li>
         <li><a href="#2">Brief Conference Agenda</a></li>
         <li><a href="#3">Join Us!</a></li>
      </ul>
   </div>
   <h3>Conference Information<a name="1"></a></h3>
   <p>You'll find information about the conference <a href="http://events.unisfair.com/index.jsp?eid=1128&amp;seid=23&amp;code=blog">here</a> as well as a link for registration. You can also see me extend a <a href="http://www.mathworks.com/company/events/conferences/matlab-virtual-conference/promotional-video.html">video welcome</a> to each of you.
   </p>
   <h3>Brief Conference Agenda<a name="2"></a></h3>
   <p>In addition to a keynote address from Jim Tung, and the following tracks:</p>
   <div>
      <ul>
         <li>Track 1 &#8211; Discover MATLAB and Simulink</li>
         <li>Track 2 &#8211; Find Out What's New</li>
         <li>Track 3 &#8211; See What Industry Experts are Doing</li>
         <li>Track 4 &#8211; Explore MATLAB and Simulink in Academia</li>
      </ul>
   </div>
   <p>The conference will have venues to meet MathWorks folks and <a href="http://events.unisfair.com/sponsors.jsp?eid=1128&amp;seid=23&amp;language-code=en&amp;country-code=US&amp;page=19238&amp;code=blog&amp;no-login=false">exhibitors</a>.
   </p>
   <h3>Join Us!<a name="3"></a></h3>
   <p>On behalf of Jim, MathWorks, and myself, we look forward to seeing you at the MATLAB Virtual Conference!</p><script language="JavaScript">
<!--

    function grabCode_b3a08d2946874e59acec9dd92714f8d4() {
        // 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='b3a08d2946874e59acec9dd92714f8d4 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' b3a08d2946874e59acec9dd92714f8d4';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

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

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_b3a08d2946874e59acec9dd92714f8d4()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.14<br /></p>
</div>
<!--
b3a08d2946874e59acec9dd92714f8d4 ##### SOURCE BEGIN #####
%% MATLAB Virtual Conference - 28 March 2012
% I am pleased to announce that we have another MATLAB Virtual Conference
% planned and taking place towards the end of March 2012.  I would like to
% formally invite you to join us on March 28, 2012. 
%% Conference Information
% You'll find information about the conference
% <http://events.unisfair.com/index.jsp?eid=1128&#038;seid=23&#038;code=Control1
% here> as well as a link for registration. You can also see me extend a
% <http://www.mathworks.com/company/events/conferences/matlab-virtual-conference/promotional-video.html
% video welcome> to each of you.
%% Brief Conference Agenda
% In addition to a keynote address from Jim Tung, and the following 
% tracks:
%
% * Track 1 â€“ Discover MATLAB and Simulink
% * Track 2 â€“ Find Out What's New
% * Track 3 â€“ See What Industry Experts are Doing
% * Track 4 â€“ Explore MATLAB and Simulink in Academia
%
% The conference will have venues to meet MathWorks folks and
% <http://events.unisfair.com/sponsors.jsp?eid=1128&#038;seid=23&#038;language-code=en&#038;country-code=US&#038;page=19238&#038;code=Control1&#038;no-login=false
% exhibitors>.
% 
%% Join Us!
% On behalf of Jim, MathWorks, and myself, we look forward to seeing you at
% the MATLAB Virtual Conference!

##### SOURCE END ##### b3a08d2946874e59acec9dd92714f8d4
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/ZrpaPHOaeSo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/03/09/matlab-virtual-conference-28-march-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/03/09/matlab-virtual-conference-28-march-2012/</feedburner:origLink></item>
		<item>
		<title>Controlling RGB LED via Potentiometer Using Arduino and MATLAB</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/BQxqosLFZ_k/</link>
		<comments>http://blogs.mathworks.com/loren/2012/02/27/controlling-rgb-led-via-potentiometer-using-arduino-and-matlab/#comments</comments>
		<pubDate>Mon, 27 Feb 2012 17:43:24 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[External interface]]></category>
		<category><![CDATA[Hardware]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=363</guid>
		<description><![CDATA[I'd like to introduce this week's guest blogger Ankit Desai. Ankit works for the Test &#38; Measurement team here at The MathWorks. Ankit has previously written about transferring data between two computers using MATLAB. In this post he will talk about using MATLAB Support Package for Arduino. Arduino is rapidly growing as a prototyping platform [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>I'd like to introduce this week's guest blogger <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/29271">Ankit Desai</a>. Ankit works for the Test &amp; Measurement team here at The MathWorks. Ankit has previously <a href="http://blogs.mathworks.com/loren/2011/05/27/transferring-data-between-two-computers-using-matlab/">written</a> about transferring data between two computers using MATLAB. In this post he will talk about using MATLAB Support Package
         for Arduino.
      </p>
      <p><a href="http://arduino.cc/en">Arduino</a> is rapidly growing as a prototyping platform for students, hobbyists and engineers. The <a href="http://www.mathworks.com/academia/arduino-software/arduino-matlab.html">MATLAB Support Package for Arduino</a> allows you to work with Arduino boards, for example <a href="http://www.arduino.cc/en/Main/arduinoBoardUno">UNO</a> and <a href="http://arduino.cc/en/Main/arduinoBoardDuemilanove">Duemilanove</a>, and allows for interactive development and debugging. The support package works on all platforms supported by MATLAB and
         does not require any additional toolboxes.
      </p>
      <p>MATLAB Support Package for Arduino uses the <a href="http://www.mathworks.com/help/techdoc/matlab_external/f105659.html">Serial Port interface</a> in MATLAB for communication with the Arduino board.
      </p>
      <p>I recently got my hands on the <a href="http://www.sparkfun.com/products/10173">Arduino Inventor Kit</a> from <a href="http://www.sparkfun.com/">Sparkfun</a>, and together with <a href="http://www.mathworks.com/matlabcentral/answers/contributors/1020339-onomitra-ghosh">Onomitra Ghosh</a>, decided to build a small project using the kit and <a href="http://www.mathworks.com/matlabcentral/fileexchange/32374">MATLAB Support Package for Arduino</a>. I decided to start with a simple project of&nbsp;controlling&nbsp;the color of an RGB LED via a potentiometer.
      </p>
      <p>The entire project was divided into three phases:</p>
      <div>
         <ol>
            <li>Setting up the Arduino and Breadboard</li>
            <li>Setting up MATLAB and Support Package</li>
            <li>Writing MATLAB Code</li>
         </ol>
      </div>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Setting up the Arduino and Breadboard</a></li>
         <li><a href="#2">Setting up MATLAB and Support Package</a></li>
         <li><a href="#3">Writing MATLAB Code</a></li>
         <li><a href="#5">Conclusion</a></li>
      </ul>
   </div>
   <h3>Setting up the Arduino and Breadboard<a name="1"></a></h3>
   <p>Depending on the platform you are working on, <a href="http://arduino.cc/en/Guide/HomePage">Arduino's website</a> has a detailed set of instructions for setting up the Arduino IDE and connecting the Arduino board. Once the setup was complete,
      I worked on the breadboard to have the setup similar to <a href="http://www.oomlout.com/a/products/ardx/circ-08/">CIRC-08</a> from the Sparkfun's Arduino Inventor Kit, except that I used an RGB LED instead of Green LED and hence instead of using just
      <b>pin 9</b> - I used <b>pins 9, 10 and 11</b>.
   </p>
   <p>At this stage the Arduino board and rest of the components were ready.</p>
   <h3>Setting up MATLAB and Support Package<a name="2"></a></h3>
   <p>MATLAB support package for Arduino comes with a server program <b>adiosrv.pde</b> that can be downloaded on the Arduino board. Once downloaded, the <b>adiosrv.pde</b> will:
   </p>
   <div>
      <ol>
         <li>Wait and listen for MATLAB commands</li>
         <li>Upon receiving MATLAB command, execute and return the result</li>
      </ol>
   </div>
   <p>The steps I performed to write/download the server program to Arduino board were as following:</p>
   <div>
      <ol>
         <li>Open Arduino IDE</li>
         <li>Select the adiosrv.pde file by navigating through File &gt; Open in the IDE</li>
         <li>Click the Upload button</li>
      </ol>
   </div>
   <p>I was now ready to code in MATLAB.</p>
   <h3>Writing MATLAB Code<a name="3"></a></h3>
   <p>MATLAB support package for Arduino provides a very easy to use function set to perform basic operations like analog read,
      analog write, digital read and digital write.
   </p>
   <p>For the purpose of this example, I followed the following sequence:</p>
   <div>
      <ol>
         <li>Read a value from analog input <b>pin 0</b>, where I connected the potentiometer
         </li>
         <li>Calculate the intensity for R,G and B colors of the LED based on the value read</li>
         <li>Write calculated R, G and B intensity to analog output <b>pins 9, 10 and 11</b></li>
         <li>Loop the sequence for predetermined amount of time</li>
      </ol>
   </div>
   <p>In MATLAB the above sequence looks like:</p><pre> % Connect to the board
 a = arduino('COM8');</pre><pre> a.pinMode(9,'output');
 a.pinMode(10,'output');
 a.pinMode(11,'output');</pre><pre> % Start the timer now
 tic;</pre><pre> while toc/60 &lt; 1 % Run for 1 minute.
 % Read analog input from analog pin 0
 % The value returned is between 0 and 1023
     sensorValue = a.analogRead(0);</pre><pre> % For potentiometer value from 0 to 511, we will fade LED from red to
 % green keeping blue at constant 0.
    if 0 &lt;= sensorValue &amp;&amp; sensorValue &lt; 512
       greenIntensity = floor(sensorValue/2.0);
       redIntensity   = 255-greenIntensity;
       blueIntensity  = 0;
    else
 % For potentiometer value from 511 to 1023, we will fade LED from
 % green to blue keeping red at constant 0.
       blueIntensity   = floor(sensorValue/2.0) - 256;
       greenIntensity  = 255 - blueIntensity;
       redIntensity    = 0;
    end</pre><pre> % Write the intensity to analog output pins
    a.analogWrite(9,redIntensity);
    a.analogWrite(10,greenIntensity);
    a.analogWrite(11,blueIntensity);
 end</pre><pre> % Close session
 delete(a);
 clear a;</pre><h3>Conclusion<a name="5"></a></h3>
   <p>
      <iframe width="560" height="315"
      src="https://www.youtube.com/embed/VsKtNoPUs0c" frameborder="0"></iframe>
      
   </p>
   <p>So why, you might ask, do I need MATLAB when I can just code it in Arduino IDE? The simple answer is - interactive development
      and debugging capabilities.
   </p>
   <p>While working on this project, there were so many instances where I wanted to see the values returned from the potentiometer
      as I was turning the knob or quickly set the RGB value of the LED. Using the Arduino IDE, I would have updated the code, re-compiled
      it and uploaded the code to the board before I can see the updates in effect. With MATLAB support package, I was able to just
      tweak the settings on the fly without any extra step.
   </p>
   <p>Make sure you check out the webinar: <a href="http://www.mathworks.com/company/events/webinars/wbnr43537.html">Learning Basic Mechatronics Concepts Using the Arduino Board and MATLAB</a>, to learn more about Analog and Digital I/O as well as DC, Servo and Stepper motor control.
   </p>
   <p>Have you used/wanted to use Arduino for any cool projects? If so, please feel free to share your project details in <a href="http://blogs.mathworks.com/?p=363#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_a8c08779e311408e909212426d411690() {
        // 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='a8c08779e311408e909212426d411690 ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' a8c08779e311408e909212426d411690';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

        author = 'Ankit Desai';
        copyright = 'Copyright 2012 The MathWorks, Inc.';

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_a8c08779e311408e909212426d411690()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.13<br /></p>
</div>
<!--
a8c08779e311408e909212426d411690 ##### SOURCE BEGIN #####
%% Controlling RGB LED via Potentiometer Using Arduino and MATLAB
% 
% I'd like to introduce this week's guest blogger
% <http://www.mathworks.com/matlabcentral/fileexchange/authors/29271 Ankit
% Desai>. Ankit works for the Test &#038; Measurement team here at The
% MathWorks. Ankit has previously
% <http://blogs.mathworks.com/loren/2011/05/27/transferring-data-between-two-computers-using-matlab/
% written> about transferring data between two computers using MATLAB. In
% this post he will talk about using MATLAB Support Package for Arduino. 
% 
% <http://arduino.cc/en Arduino> is rapidly growing as a prototyping
% platform for students, hobbyists and engineers. The
% <http://www.mathworks.com/academia/arduino-software/arduino-matlab.html
% MATLAB Support Package for Arduino> allows you to work with Arduino
% boards, for example <http://www.arduino.cc/en/Main/arduinoBoardUno UNO>
% and <http://arduino.cc/en/Main/arduinoBoardDuemilanove Duemilanove>, and
% allows for interactive development and debugging. The support package
% works on all platforms supported by MATLAB and does not require any
% additional toolboxes.
%
% MATLAB Support Package for Arduino uses the
% <http://www.mathworks.com/help/techdoc/matlab_external/f105659.html
% Serial Port interface> in MATLAB for communication with the Arduino
% board.   
% 
% I recently got my hands on the <http://www.sparkfun.com/products/10173
% Arduino Inventor Kit> from <http://www.sparkfun.com/ Sparkfun>, and
% together with
% <http://www.mathworks.com/matlabcentral/answers/contributors/1020339-onomitra-ghosh
% Onomitra Ghosh>, decided to build a small project using the kit and
% <http://www.mathworks.com/matlabcentral/fileexchange/32374 MATLAB Support
% Package for Arduino>. I decided to start with a simple project
% ofÂ controllingÂ the color of an RGB LED via a potentiometer. 
%
% The entire project was divided into three phases:
% 
% # Setting up the Arduino and Breadboard
% # Setting up MATLAB and Support Package
% # Writing MATLAB Code
%
%% Setting up the Arduino and Breadboard
% 
% Depending on the platform you are working
% on, <http://arduino.cc/en/Guide/HomePage Arduino's website> has a detailed set 
% of instructions for setting up the Arduino IDE and connecting the Arduino
% board. Once the setup was complete, I worked on the breadboard to have
% the setup similar to <http://www.oomlout.com/a/products/ardx/circ-08/
% CIRC-08> from the Sparkfun's Arduino Inventor Kit, except that I used an
% RGB LED instead of Green LED and hence instead of using just *pin 9* - I
% used *pins 9, 10 and 11*.
%
% At this stage the Arduino board and rest of the components were ready.
%
%% Setting up MATLAB and Support Package
% 
% MATLAB support package for Arduino comes with a server program
% *adiosrv.pde* that can be downloaded on the Arduino board. Once
% downloaded, the *adiosrv.pde* will: 
% 
% # Wait and listen for MATLAB commands
% # Upon receiving MATLAB command, execute and return the result
% 
% The steps I performed to write/download the server program to Arduino
% board were as following: 
% 
% # Open Arduino IDE
% # Select the adiosrv.pde file by navigating through File > Open in the IDE
% # Click the Upload button
% 
% I was now ready to code in MATLAB.
% 
%% Writing MATLAB Code
% 
% MATLAB support package for Arduino provides a very easy to use function set to
% perform basic operations like analog read, analog write, digital read and
% digital write. 
% 
% For the purpose of this example, I followed the following sequence:
% 
% # Read a value from analog input *pin 0*, where I connected the potentiometer
% # Calculate the intensity for R,G and B colors of the LED based on the value read
% # Write calculated R, G and B intensity to analog output *pins 9, 10 and
% 11*
% # Loop the sequence for predetermined amount of time
% 
% In MATLAB the above sequence looks like:
%%
%
%   % Connect to the board
%   a = arduino('COM8');
%
%   a.pinMode(9,'output');
%   a.pinMode(10,'output');
%   a.pinMode(11,'output');
% 
%   % Start the timer now
%   tic;
%
%   while toc/60 < 1 % Run for 1 minute.
%   % Read analog input from analog pin 0
%   % The value returned is between 0 and 1023
%       sensorValue = a.analogRead(0);
%   
%   % For potentiometer value from 0 to 511, we will fade LED from red to
%   % green keeping blue at constant 0. 
%      if 0 <= sensorValue &#038;& sensorValue < 512
%         greenIntensity = floor(sensorValue/2.0);
%         redIntensity   = 255-greenIntensity;
%         blueIntensity  = 0;
%      else
%   % For potentiometer value from 511 to 1023, we will fade LED from
%   % green to blue keeping red at constant 0.
%         blueIntensity   = floor(sensorValue/2.0) - 256;
%         greenIntensity  = 255 - blueIntensity;
%         redIntensity    = 0;
%      end
%
%   % Write the intensity to analog output pins
%      a.analogWrite(9,redIntensity);
%      a.analogWrite(10,greenIntensity);
%      a.analogWrite(11,blueIntensity);
%   end
% 
%   % Close session
%   delete(a);
%   clear a;

%% Conclusion
% 
% <html>
% <iframe width="560" height="315"
% src="https://www.youtube.com/embed/VsKtNoPUs0c" frameborder="0"></iframe>
% </html>
%
% So why, you might ask, do I need MATLAB when I can just code it in
% Arduino IDE? The simple answer is - interactive development and
% debugging capabilities. 
% 
% While working on this project, there were so many instances where I
% wanted to see the values returned from the potentiometer as I was turning
% the knob or quickly set the RGB value of the LED. Using the Arduino
% IDE, I would have updated the code, re-compiled it and uploaded
% the code to the board before I can see the updates in effect. With MATLAB
% support package, I was able to just tweak the settings on the fly without any
% extra step. 
% 
% Make sure you check out the webinar:
% <http://www.mathworks.com/company/events/webinars/wbnr43537.html Learning
% Basic Mechatronics Concepts Using the Arduino Board and MATLAB>, to learn
% more about Analog and Digital I/O as well as DC, Servo and Stepper motor
% control.  
%
% Have you used/wanted to use Arduino for any cool projects? If so, please
% feel free to share your project details in
% <http://blogs.mathworks.com/?p=363#respond here>.
##### SOURCE END ##### a8c08779e311408e909212426d411690
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/BQxqosLFZ_k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/02/27/controlling-rgb-led-via-potentiometer-using-arduino-and-matlab/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/02/27/controlling-rgb-led-via-potentiometer-using-arduino-and-matlab/</feedburner:origLink></item>
		<item>
		<title>Separating Errors from Output in a Deployed Application</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/K9DIJL4iLFE/</link>
		<comments>http://blogs.mathworks.com/loren/2012/02/15/separating-errors-from-output-in-a-deployed-application/#comments</comments>
		<pubDate>Wed, 15 Feb 2012 16:59:14 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[Deployment]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=352</guid>
		<description><![CDATA[Guest blogger Peter Webb returns with another in an occasional series of postings about application deployment. Contents Errors are Different! A Brief Review of the Application Splitting the Error and Output Streams Emphasizing Error Messages Seeing the Differences Errors are Different! By default, standalone applications display both ordinary output and and errors via the same [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>Guest blogger <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/4660">Peter Webb</a> returns with another in an <a href="http://blogs.mathworks.com/loren/category/deployment/">occasional series</a> of postings about application deployment.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Errors are Different!</a></li>
         <li><a href="#2">A Brief Review of the Application</a></li>
         <li><a href="#3">Splitting the Error and Output Streams</a></li>
         <li><a href="#4">Emphasizing Error Messages</a></li>
         <li><a href="#5">Seeing the Differences</a></li>
      </ul>
   </div>
   <h3>Errors are Different!<a name="1"></a></h3>
   <p>By default, standalone applications display both ordinary output and and errors via the same channel. This can be convenient,
      as it makes capturing all the output relatively simple. With this simplicity comes a hidden danger: error messages may get
      lost if the application prints out a lot of messages. In this final installment of my <a href="http://blogs.mathworks.com/loren/category/deployment/">series of posts</a> about redirecting program output, I'm going to show you how to treat <a href="http://www.mathworks.com/help/techdoc/ref/error.html">errors</a> differently than other types of messages. One reason for doing so is to make error messages more obvious, so they are easier
      to find. When I'm looking through a long listing of  program output, I'm often scanning primarily for error messages, because
      errors indicate some intervention is necessary. I'd like the errors to be emphasized or decorated so I'll spot them quickly.
   </p>
   <p>Applications and shared libraries created by <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/compiler/br5w5e9-1.html">MATLAB Compiler</a> split the output from <a href="http://www.mathworks.com/products/matlab">MATLAB</a> <a href="http://www.mathworks.com/help/techdoc/ref/function.html">functions</a>, into two <i>streams</i>, one for errors and one for all other types of output, including warnings. Since MATLAB Compiler-generated components allow
      you to <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/compiler/f2-998954.html#f2-1008529">install a separate handler</a> for each of these streams, it is conceptually simple to emphasize error messages.
   </p>
   <h3>A Brief Review of the Application<a name="2"></a></h3>
   <p><tt>monitor</tt> is a C program that calls a single MATLAB function, <tt>sendmessages</tt>. The MATLAB function displays three kinds of output: some informational text, a warning message and an error message. <tt>monitor.c</tt> relies on three monitoring functions, <tt>StartMonitoring</tt>, <tt>MonitorHandler</tt> and <tt>StopMonitoring</tt>, to redirect its output to a user-visible window. Separate, platform-specific files contain different sets of monitoring
      functions.
   </p>
   <p><a href="http://www.mathworks.com/matlabcentral/fileexchange/32598-liberating-deployed-application-output-from-the-console-window">Download the source code</a> for the <tt>monitor</tt> program from <a href="http://www.mathworks.com/matlabcentral/">MATLAB Central</a>. See the <tt>monitorREADME</tt> in the ZIP file for a description of each of the downloaded files and complete directions for building the application.
   </p>
   <h3>Splitting the Error and Output Streams<a name="3"></a></h3>
   <p>The generated library initialization function <tt>libmsgfcnInitializeWithHandlers</tt> takes two input arguments: an error message handler and a print message handler. The example <tt>monitor.c</tt> I discussed in last week's post installs the same handler, the function <tt>MonitorHandler</tt>, for both the <i>error</i> and the <i>print</i> output streams:
   </p><pre> if (!libmsgfcnInitializeWithHandlers(MonitorHandler, MonitorHandler))</pre><p>Change the first parameter to a specialized error handler, the <tt>ErrorHandler</tt> function, and the <tt>monitor</tt> program decorates the error messages it displays, making them easier to see.
   </p><pre> if (!libmsgfcnInitializeWithHandlers(ErrorHandler, MonitorHandler))</pre><h3>Emphasizing Error Messages<a name="4"></a></h3>
   <p>I've chosen to emphasize error messages in two different ways. On UNIX the monitor window displays error messages in red.
      The UNIX <tt>ErrorHandler</tt> function uses X terminal <a href="http://www.frexx.de/xterm-256-notes/">escape codes</a> to set the color of the displayed text. <tt>ErrorHandler</tt> sends the sequence <tt>ESC [ 1;31m</tt> to set the text to red, outputs the error message, and then restores the foreground color to black with the sequence <tt>ESC [ 1;30m</tt>.
   </p><pre>int ErrorHandler(const char *s)
{
    const int csi = 0x9b;
    const char *redOn = "1;31m";
    const char *redOff = "1;30m";</pre><pre>    time_t now = time(NULL);
    char nowIsTheHour[128];
    fwrite(&amp;csi, sizeof(int), 1, tmpLog);
    fprintf(tmpLog, "%s", redOn);
    sprintf(nowIsTheHour, "%s", ctime(&amp;now));
    fprintf(tmpLog, nowIsTheHour);
    fprintf(tmpLog, "%s\n", s);
    fwrite(&amp;csi, sizeof(int), 1, tmpLog);
    fprintf(tmpLog, "%s", redOff);
    return strlen(s)+strlen(nowIsTheHour)+1;
}</pre><p>The UNIX monitoring mechanism sends its output to a temporary file, the contents of which are displayed in an X terminal running
      <tt>tail -f</tt>. Refer to the <a href="http://blogs/mathworks.com/loren/?p=320">previous post</a> in this series for complete details of the implementation.
   </p>
   <p>The monitoring mechanism in the Windows program <tt>monitorWinDialog</tt> uses a dialog box containing a <a href="http://msdn.microsoft.com/en-us/library/bb775146%28VS.85%29.aspx"><tt>ListBox</tt></a>. The <a href="http://msdn.microsoft.com/en-us/library/ms645469%28VS.85%29.aspx"><tt>DialogProc</tt></a> function (the function that handles events directed at the dialog box), prefixes a line of five asterixes to error messages
      before displaying them:
   </p><pre>case ERROR_MESSAGE:
    strcpy(buffer, "***** ");
    strcat(buffer, (const char *)lParam);
    ListBox_AddString(GetDlgItem(box, IDC_LIST1),
                      (const char *)buffer);
    break;</pre><p>The error handler function <tt>ErrorHandler</tt> in the <a href="http://support.microsoft.com/kb/308427">Microsoft Windows event log</a> version, <tt>monitorWinEvents</tt> calls <a href="http://msdn.microsoft.com/en-us/library/aa363679%28VS.85%29.aspx"><tt>ReportEvent</tt></a> with an event type of <tt>EVENTLOG_ERROR_TYPE</tt>.
   </p><pre>if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, EXAMPLE_CATEGORY,
                 INFORMATIONAL_MESSAGE, NULL, 1, 0,
                 (LPCSTR*)pInsertStrings, NULL))</pre><p>In response, the <a href="http://en.wikipedia.org/wiki/Event_Viewer">event log viewer</a> displays a stop-sign icon next to the event. The print handler <tt>MonitorHandler</tt> creates events with an event type of <tt>EVENTLOG_INFORMATION_TYPE</tt>, causing the event logger to display a "talk bubble" icon next to the event.
   </p>
   <h3>Seeing the Differences<a name="5"></a></h3>
   <p>Once you've changed <tt>monitor.c</tt> to install separate handlers on the error and print message streams, build and run the application.
   </p>
   <p>First use MATLAB Compiler to create the shared library containing <tt>sendmessages</tt>:
   </p><pre>&gt;&gt; mcc -W lib:libmsgfcn -T link:lib sendmessages.m</pre><p>Then, use <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/compiler/mbuild.html"><tt>mbuild</tt></a> to build the main program and link it with the shared library:
   </p>
   <p>(UNIX): <tt>mbuild -g monitor.c monitorUNIX.c -L. -lmsgfcn</tt></p>
   <p>(Windows) -- two commands because there are two programs:</p><pre>mbuild -g monitorWinDialog.c monitor.c WinLogger.rc libmsgfcn.lib</pre><pre>mbuild -g monitorWinEvents.c monitor.c libmsgfcn.lib</pre><p>The first command builds the dialog box version (<tt>monitorWinDialog.exe</tt>) and the second command builds the event log version (<tt>monitorWinEvents.exe</tt>).
   </p>
   <p>Now run it. The program takes three input arguments: the informational message, the warning and the error message.</p>
   <p>(UNIX):    <tt>./monitor information "look out!" oops</tt></p>
   <p>(Windows): <tt>monitorWinDialog.exe information "look out!" oops</tt></p>
   <p>It should be easy to pick out the error message in the program output.</p>
   <p>That's all I've got to say about managing errors and output in a deployed application. Do your applications do things differently?
      Are any of these ideas going to be useful to you? What would you like to see the Compiler do differently? <a href="http://blogs/mathworks.com/loren/?p=352#respond">Let me know</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_1036c44880d64e4aa4d72a1ca620200b() {
        // 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='1036c44880d64e4aa4d72a1ca620200b ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 1036c44880d64e4aa4d72a1ca620200b';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

        author = 'Peter Webb';
        copyright = 'Copyright 2012 The MathWorks, Inc.';

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_1036c44880d64e4aa4d72a1ca620200b()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.13<br /></p>
</div>
<!--
1036c44880d64e4aa4d72a1ca620200b ##### SOURCE BEGIN #####
%% Separating Errors from Output in a Deployed Application
% Guest blogger 
% <http://www.mathworks.com/matlabcentral/fileexchange/authors/4660 Peter Webb>
% returns with another in an 
% <http://blogs.mathworks.com/loren/category/deployment/ occasional series>
% of postings about application deployment. 
%% Errors are Different!
% By default, standalone applications display both ordinary output and 
% and errors via the same channel. This can be convenient, as it makes
% capturing all the output relatively simple. With this simplicity comes a
% hidden danger: error messages may get lost if the application prints out
% a lot of messages. In this final installment of my 
% <http://blogs.mathworks.com/loren/category/deployment/ series of posts>
% about redirecting program output, I'm going to show you how to treat 
% <http://www.mathworks.com/help/techdoc/ref/error.html errors> differently
% than other types of messages. One reason for doing so is to make error
% messages more obvious, so they are easier to find. When I'm looking 
% through a long listing of  program output, I'm often scanning primarily
% for error messages, because errors indicate some intervention is necessary. 
% I'd like the errors to be emphasized or decorated so I'll spot them
% quickly.
%
% Applications and shared libraries created by 
% <http://www.mathworks.com/access/helpdesk/help/toolbox/compiler/br5w5e9-1.html 
% MATLAB Compiler> split the
% output from
% <http://www.mathworks.com/products/matlab MATLAB>
% <http://www.mathworks.com/help/techdoc/ref/function.html functions>,
% into two _streams_, one for errors and one
% for all other types of output, including warnings. Since MATLAB 
% Compiler-generated components allow you to 
% <http://www.mathworks.com/access/helpdesk/help/toolbox/compiler/f2-998954.html#f2-1008529 
% install a separate handler> for
% each of these streams, it is conceptually simple to emphasize error
% messages.
%
%% A Brief Review of the Application
% |monitor| is a C program that calls a single MATLAB function,
% |sendmessages|. The MATLAB function displays three kinds of output: some
% informational text, a warning message and an error message. |monitor.c|
% relies on three monitoring functions, |StartMonitoring|, |MonitorHandler|
% and |StopMonitoring|, to redirect its output to a user-visible window.
% Separate, platform-specific files contain different sets of monitoring
% functions. 
%
% <http://www.mathworks.com/matlabcentral/fileexchange/32598-liberating-deployed-application-output-from-the-console-window 
% Download the source code> for the |monitor| program 
% from <http://www.mathworks.com/matlabcentral/ MATLAB Central>. See the
% |monitorREADME| in the ZIP file for a description of each of the downloaded 
% files and complete directions for building the application.
%
%% Splitting the Error and Output Streams
% The generated library initialization function
% |libmsgfcnInitializeWithHandlers| takes two input arguments: an error
% message handler and a print message handler. The example |monitor.c| I
% discussed in last week's post installs the same handler, the function
% |MonitorHandler|, for both the _error_ and the _print_ output streams:
%
%   if (!libmsgfcnInitializeWithHandlers(MonitorHandler, MonitorHandler)) 
%
% Change the first parameter to a specialized error handler, the
% |ErrorHandler| function, and the |monitor| program decorates the error
% messages it displays, making them easier to see.
% 
%   if (!libmsgfcnInitializeWithHandlers(ErrorHandler, MonitorHandler)) 
%
%% Emphasizing Error Messages
% I've chosen to emphasize error messages in two different ways. On UNIX 
% the monitor window displays error messages in red. The UNIX
% |ErrorHandler| function uses X terminal 
% <http://www.frexx.de/xterm-256-notes/ escape codes> to set the color of
% the displayed text. |ErrorHandler| sends the sequence |ESC [ 1;31m| 
% to set the text to red, outputs the error message, and then restores 
% the foreground color to black with the sequence |ESC [ 1;30m|. 
%
%  int ErrorHandler(const char *s)
%  {
%      const int csi = 0x9b;
%      const char *redOn = "1;31m";
%      const char *redOff = "1;30m";
%  
%      time_t now = time(NULL);
%      char nowIsTheHour[128];
%      fwrite(&#038;csi, sizeof(int), 1, tmpLog);
%      fprintf(tmpLog, "%s", redOn);
%      sprintf(nowIsTheHour, "%s", ctime(&#038;now));
%      fprintf(tmpLog, nowIsTheHour);
%      fprintf(tmpLog, "%s\n", s);
%      fwrite(&#038;csi, sizeof(int), 1, tmpLog);
%      fprintf(tmpLog, "%s", redOff);
%      return strlen(s)+strlen(nowIsTheHour)+1;
%  }
%
% The UNIX monitoring mechanism sends its output to a temporary file, the
% contents of which are displayed in an X terminal running |tail -f|.
% Refer to the 
% <http://blogs/mathworks.com/loren/?p=320 previous post>
% in this series for complete details of the
% implementation.
%
% The monitoring mechanism in the Windows program |monitorWinDialog| 
% uses a dialog box containing a 
% <http://msdn.microsoft.com/en-us/library/bb775146%28VS.85%29.aspx
% |ListBox|>. The 
% <http://msdn.microsoft.com/en-us/library/ms645469%28VS.85%29.aspx |DialogProc|>
% function (the function that handles events directed at the dialog box),
% prefixes a line of five asterixes to error messages before displaying 
% them: 
%
%  case ERROR_MESSAGE:
%      strcpy(buffer, "***** ");
%      strcat(buffer, (const char *)lParam);
%      ListBox_AddString(GetDlgItem(box, IDC_LIST1), 
%                        (const char *)buffer);
%      break;
%
% The error handler function |ErrorHandler| in the 
% <http://support.microsoft.com/kb/308427 Microsoft Windows event log>
% version, |monitorWinEvents| calls 
% <http://msdn.microsoft.com/en-us/library/aa363679%28VS.85%29.aspx 
% |ReportEvent|> with an event type of |EVENTLOG_ERROR_TYPE|.
%
%  if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, EXAMPLE_CATEGORY, 
%                   INFORMATIONAL_MESSAGE, NULL, 1, 0, 
%                   (LPCSTR*)pInsertStrings, NULL))
%
% In response, the 
% <http://en.wikipedia.org/wiki/Event_Viewer event log viewer>
% displays a stop-sign icon next to 
% the event. The print handler |MonitorHandler| creates events with an
% event type of |EVENTLOG_INFORMATION_TYPE|, causing the event logger to
% display a "talk bubble" icon next to the event. 
%
%% Seeing the Differences
% Once you've changed |monitor.c| to install separate handlers on the error
% and print message streams, build and run the application.
%
% First use MATLAB Compiler to create the shared library containing 
% |sendmessages|:
%
%  >> mcc -W lib:libmsgfcn -T link:lib sendmessages.m
%
% Then, use 
% <http://www.mathworks.com/access/helpdesk/help/toolbox/compiler/mbuild.html 
% |mbuild|> to build the main program and link it with the 
% shared library:
%
% (UNIX): |mbuild -g monitor.c monitorUNIX.c -L. -lmsgfcn|
%
% (Windows) REPLACE_WITH_DASH_DASH two commands because there are two programs: 
%
%  mbuild -g monitorWinDialog.c monitor.c WinLogger.rc libmsgfcn.lib
%
%  mbuild -g monitorWinEvents.c monitor.c libmsgfcn.lib
%
% The first command builds the dialog box version (|monitorWinDialog.exe|)
% and the second command builds the event log version 
% (|monitorWinEvents.exe|).
% 
% Now run it. The program takes three input arguments: the informational
% message, the warning and the error message.
%
% (UNIX):    |./monitor information "look out!" oops|
%
% (Windows): |monitorWinDialog.exe information "look out!" oops|
%
% It should be easy to pick out the error message in the program output.
%
% That's all I've got to say about managing errors and output in a deployed
% application. Do your applications do things differently? Are any of these
% ideas going to be useful to you? What would you like to see the Compiler
% do differently? <http://blogs/mathworks.com/loren/?p=352#respond Let me
% know>.


##### SOURCE END ##### 1036c44880d64e4aa4d72a1ca620200b
--><img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/K9DIJL4iLFE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/02/15/separating-errors-from-output-in-a-deployed-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/02/15/separating-errors-from-output-in-a-deployed-application/</feedburner:origLink></item>
		<item>
		<title>Using GPUs in MATLAB</title>
		<link>http://feedproxy.google.com/~r/mathworks/loren/~3/ouvhwaD6oEY/</link>
		<comments>http://blogs.mathworks.com/loren/2012/02/06/using-gpus-in-matlab/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 16:41:38 +0000</pubDate>
		<dc:creator>Loren Shure</dc:creator>
				<category><![CDATA[New Feature]]></category>
		<category><![CDATA[Parallel]]></category>

		<guid isPermaLink="false">http://blogs.mathworks.com/loren/?p=346</guid>
		<description><![CDATA[Today I&#8217;d like to introduce guest blogger Sarah Wait Zaranek who works for the MATLAB Marketing team. Sarah previously has written about speeding up code from a customer to get acceptable performance. She will be discussing how to use GPUs to accelerate your MATLAB applications. Contents Overview GPU Background Learning About Our GPU A Simple [...]]]></description>
			<content:encoded><![CDATA[<div xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd" class="content">
   <introduction>
      <p>Today I&#8217;d like to introduce guest blogger <a href="mailto:sarah.zaranek@mathworks.com">Sarah Wait Zaranek</a> who works for the MATLAB Marketing team. Sarah previously has <a href="http://blogs.mathworks.com/loren/2008/06/25/speeding-up-matlab-applications/">written</a> about speeding up code from a customer to get acceptable performance. She will be discussing how to use GPUs to accelerate
         your MATLAB applications.
      </p>
   </introduction>
   <h3>Contents</h3>
   <div>
      <ul>
         <li><a href="#1">Overview</a></li>
         <li><a href="#2">GPU Background</a></li>
         <li><a href="#5">Learning About Our GPU</a></li>
         <li><a href="#7">A Simple Example using Overloaded Functions</a></li>
         <li><a href="#12">Speedup For Our Simple Example</a></li>
         <li><a href="#14">Understanding and Limiting Your Data Transfer Overhead</a></li>
         <li><a href="#16">Solving the Wave Equation</a></li>
         <li><a href="#20">Code Changes to Run Algorithm on GPU</a></li>
         <li><a href="#21">Code Changes to Transfer Data to the GPU and Back Again</a></li>
         <li><a href="#24">Comparing CPU and GPU Execution Speeds</a></li>
         <li><a href="#27">Other Ways to Use the GPU with MATLAB</a></li>
         <li><a href="#28">Your Thoughts?</a></li>
      </ul>
   </div>
   <h3>Overview<a name="1"></a></h3>
   <p>In this post, we first will introduce the basics of using the GPU with MATLAB and then move onto solving a 2nd-order wave
      equation using this GPU functionality. This blog post is inspired by a recent MATLAB Digest <a href="http://www.mathworks.com/company/newsletters/articles/gpu-programming-in-matlab.html">article</a> on GPU Computing that I coauthored with one of our developers, Jill Reese. Since the original demo was made, the GPU functions
      available in MATLAB have grown. If you compare the code below to the code in the paper- they are slightly different, reflecting
      these new capabilites. Additionally, small changes were made to enable easier explanation of the code in this blog format.
      The GPU functionality shown in this post requires the Parallel Computing Toolbox.
   </p>
   <h3>GPU Background<a name="2"></a></h3>
   <p>Originally used to accelerate graphics rendering, GPUs are now increasingly applied to scientific calculations. Unlike a traditional
      CPU, which includes no more than a handful of cores, a GPU has a massively parallel array of integer and floating-point processors,
      as well as dedicated, high-speed memory. A typical GPU comprises hundreds of these smaller processors.  These processors can
      be used to greatly speed-up particular types of applications.
   </p>
   <p>A good rule of thumb is that your problem may be a good fit for the GPU if it is:</p>
   <div>
      <ul>
         <li>Massively parallel: The computations can be broken down into hundreds or thousands of independent units of work.  You will
            see the best performance when all of the cores are kept busy, exploiting the inherent parallel nature of the GPU. Seemingly
            simple, vectorized MATLAB calculations on arrays with hundreds of thousands of elements often can fit into this category.
         </li>
      </ul>
   </div>
   <div>
      <ul>
         <li>Computationally intensive: The time spent on computation significantly exceeds the time spent on transferring data to and
            from GPU memory. Because a GPU is attached to the host CPU via the PCI Express bus, the memory access is slower than with
            a traditional CPU. This means that your overall computational speedup is limited by the amount of data transfer that occurs
            in your algorithm.
         </li>
      </ul>
   </div>
   <p>Applications that do not satisfy these criteria might actually run more slowly on a GPU than on a CPU.</p>
   <h3>Learning About Our GPU<a name="5"></a></h3>
   <p>With that background, we can now start working with the GPU in MATLAB. Let's start first by querying our GPU to see just what
      we are working with:
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">gpuDevice</pre><pre style="font-style:oblique">ans = 
  parallel.gpu.CUDADevice handle
  Package: parallel.gpu

  Properties:
                      Name: 'Tesla C2050 / C2070'
                     Index: 1
         ComputeCapability: '2.0'
            SupportsDouble: 1
             DriverVersion: 4
        MaxThreadsPerBlock: 1024
          MaxShmemPerBlock: 49152
        MaxThreadBlockSize: [1024 1024 64]
               MaxGridSize: [65535 65535]
                 SIMDWidth: 32
               TotalMemory: 3.1820e+009
                FreeMemory: 2.6005e+009
       MultiprocessorCount: 14
              ClockRateKHz: 1147000
               ComputeMode: 'Default'
      GPUOverlapsTransfers: 1
    KernelExecutionTimeout: 1
          CanMapHostMemory: 1
           DeviceSupported: 1
            DeviceSelected: 1
</pre><p>We are running on a Tesla C2050.  Currently, Parallel Computing Toolbox supports NVDIA GPUs with Compute Capability 1.3 or
      greater. <a href="http://www.nvidia.com/object/cuda_gpus.html">Here</a> is a link to see if your card is supported.
   </p>
   <h3>A Simple Example using Overloaded Functions<a name="7"></a></h3>
   <p>Over 100 operations (e.g. <tt>fft</tt>, <tt>ifft</tt>, <tt>eig</tt>) are now available as built-in MATLAB functions that can be executed directly on the GPU by providing an input argument of
      the type GPUArray. These GPU-enabled functions are overloaded&#8212;in other words, they operate differently depending on the data
      type of the arguments passed to them. <a href="http://www.mathworks.com/help/releases/R2011b/toolbox/distcomp/bsic4fr-1.html">Here</a> is a list of all the overloaded functions.
   </p>
   <p>Let's create a GPUArray and perform a <tt>fft</tt> using the GPU. However, let's first do this on the CPU so that we can see the difference in code and performance
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">A1 = rand(3000,3000);
tic;
B1 = fft(A1);
time1 = toc;</pre><p>To perform the same operation on the GPU, we first use <tt>gpuArray</tt> to transfer data from the MATLAB workspace to device memory. Then we can run <tt>fft</tt>, which is one of the overloaded functions on that data:
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">A2 = gpuArray(A1);
tic;
B2 = fft(A2);
time2 = toc;</pre><p>The second case is executed on the GPU rather than the CPU since its input (a GPUArray) is held on the GPU. The result, <tt>B2</tt>, is stored on the GPU. However, it is still visible in the MATLAB workspace. By running <tt>class(B2)</tt>, we can see that it is also a GPUArray.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">class(B2)</pre><pre style="font-style:oblique">ans =
parallel.gpu.GPUArray
</pre><p>To bring the data back to the CPU, we run <tt>gather</tt>.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">B2 = gather(B2);
class(B2)</pre><pre style="font-style:oblique">ans =
double
</pre><p><tt>B2</tt> is now on the CPU and has a class of double.
   </p>
   <h3>Speedup For Our Simple Example<a name="12"></a></h3>
   <p>In this simple example, we can calculate the speedup of performing the <tt>fft</tt> on our data.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">speedUp = time1/time2;
disp(speedUp)</pre><pre style="font-style:oblique">    3.6122
</pre><p>It looks like our <tt>fft</tt> is running ~3.5x faster on the GPU. This is pretty good, especially since <tt>fft</tt> is multi-threaded in core MATLAB. However, to perform a realistic comparison, we should really include the time spent transferring
      the vector to and from the GPU. If we do that - we find that our acceleration is greatly reduced. Let's see what happens if
      we include the time to do our data transfer.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">tic;
A3 = gpuArray(A1);
B3 = fft(A3);
B3 = gather(B3);
time3 = toc;

speedUp = time1/time3;
disp(speedUp)</pre><pre style="font-style:oblique">    0.5676
</pre><h3>Understanding and Limiting Your Data Transfer Overhead<a name="14"></a></h3>
   <p>Data transfer overhead can become so significant that it degrades the application's overall performance, especially if you
      repeatedly exchange data between the CPU and GPU to execute relatively few computationally intensive operations. However not
      all hope is lost!  By limiting the data transfer between the GPU and the CPU, we can still acheive speedup.
   </p>
   <p>Instead of creating the data on the CPU and transferring it to the GPU - we can just create on the GPU directly.  There are
      several <a href="http://www.mathworks.com/help/releases/R2011b/toolbox/distcomp/bsic4fr-1.html">constructors</a> available as well as constructor-like functions such as <tt>meshgrid</tt>. Let's see how that effects our time.  To be accurate, we should also retime the original serial code including the time
      it takes to generate the random matrix on the CPU.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">tic;
A4 = rand(3000,3000);
B4 = fft(A4);
time4 = toc;

tic;
A5 = parallel.gpu.GPUArray.rand(3000,3000);
B5 = fft(A5);
B5 = gather(B5);
time5 = toc;

speedUp = time4/time5;
disp(speedUp);</pre><pre style="font-style:oblique">    1.4100
</pre><p>This is better, although we still do see the influence of gathering the data back from the GPU.  In this simple demo, the
      effect is exaggerated because we are running a single, already fast operation on the GPU. It is more efficient to perform
      several operations on the data while it is on the GPU, bringing the data back to the CPU only when required.
   </p>
   <h3>Solving the Wave Equation<a name="16"></a></h3>
   <p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/346/WaveEquation.gif"> </p>
   <p>To put the above example into context, let's use the same GPU functionality on a more "real-world" problem. To do this,  we
      are going to solve a second-order wave equation:
   </p>
   <p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/346/UsingGPUs_eq30596.png"> </p>
   <p>The algorithm we use to solve the wave equation combines a spectral method in space and a second-order central finite difference
      method in time. Specifically, we apply the Chebyshev spectral method, which uses Chebyshev polynomials as the basis functions.
      Our example is largely based on an example in Trefethen's book: <a href="http://www.mathworks.com/support/books/book48110.html">"Spectral Methods in MATLAB"</a></p>
   <h3>Code Changes to Run Algorithm on GPU<a name="20"></a></h3>
   <p>When accelerating our alogrithm, we focus on speeding up the code within the main time stepping while-loop. The operations
      in that part of the code (e.g. <tt>fft</tt> and <tt>ifft</tt>, matrix multiplication) are all overloaded functions that work with the GPU. As a result, we do not need to change the algorithm
      in any way to execute it on a GPU. We get to simply transfer the data to the GPU and back to the CPU when finished.
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type(<span style="color: #A020F0">'stepSolution.m'</span>)</pre><pre style="font-style:oblique">
function [vv,vvold] = stepsolution(vv,vvold,ii,N,dt,W1T,W2T,W3T,W4T,...
                                        WuxxT1,WuxxT2,WuyyT1,WuyyT2)
    V = [vv(ii,:) vv(ii,N:-1:2)];
    U = real(fft(V.')).';
    
    W1test = (U.*W1T).';
    W2test = (U.*W2T).';
    W1 = (real(ifft(W1test))).';
    W2 = (real(ifft(W2test))).';
    
    % Calculating 2nd derivative in x
    uxx(ii,ii) = W2(:,ii).* WuxxT1 - W1(:,ii).*WuxxT2;
    uxx([1,N+1],[1,N+1]) = 0;
    
    V = [vv(:,ii); vv((N:-1:2),ii)];
    U = real(fft(V));
    
    W1 = real(ifft(U.*W3T));
    W2 = real(ifft(U.*W4T));
    
    % Calculating 2nd derivative in y
    uyy(ii,ii) = W2(ii,:).* WuyyT1 - W1(ii,:).*WuyyT2;
    uyy([1,N+1],[1,N+1]) = 0;
    
    % Computing new value using 2nd order central finite difference in
    % time
    vvnew = 2*vv - vvold + dt*dt*(uxx+uyy);
    vvold = vv; vv = vvnew;

end


</pre><h3>Code Changes to Transfer Data to the GPU and Back Again<a name="21"></a></h3>
   <p>The variables <tt>dt</tt>, <tt>x</tt>, <tt>index1</tt>, and <tt>index2</tt> are calculated on the CPU and transferred over to the GPU using <tt>gpuArray</tt>.
   </p>
   <p>For example:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">N = 256;
index1 = 1i*[0:N-1 0 1-N:-1];

index1 = gpuArray(index1);</pre><p>For the rest of the variables, we create them directly on the GPU using the overloaded versions of the transpose operator
      (<tt>'</tt>), <tt>repmat</tt> ,and <tt>meshgrid</tt>.
   </p>
   <p>For example:</p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">W1T = repmat(index1,N-1,1);</pre><p>When, we are done with all our calculations on the GPU, we use <tt>gather</tt> once to bring data back from the GPU. Note, that we don't have to transfer our data back to the CPU between time steps. This
      all comes together to look like this:
   </p><pre style="background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)">type <span style="color: #A020F0">WaveGPU.m</span></pre><pre style="font-style:oblique">
function vvg = WaveGPU(N,Nsteps)
%% Solving 2nd Order Wave Equation Using Spectral Methods
% This example solves a 2nd order wave equation: utt = uxx + uyy, with u =
% 0 on the boundaries. It uses a 2nd order central finite difference in
% time and a Chebysehv spectral method in space (using FFT). 
%
% The code has been modified from an example in Spectral Methods in MATLAB
% by Trefethen, Lloyd N.

% Points in X and Y
x = cos(pi*(0:N)/N); % using Chebyshev points

% Send x to the GPU
x = gpuArray(x);
y = x';

% Calculating time step
dt = 6/N^2;

% Setting up grid
[xx,yy] = meshgrid(x,y);

% Calculate initial values
vv = exp(-40*((xx-.4).^2 + yy.^2));
vvold = vv;

ii = 2:N;
index1 = 1i*[0:N-1 0 1-N:-1];
index2 = -[0:N 1-N:-1].^2;

% Sending data to the GPU
dt = gpuArray(dt);
index1 = gpuArray(index1);
index2 = gpuArray(index2);

% Creating weights used for spectral differentiation 
W1T = repmat(index1,N-1,1);
W2T = repmat(index2,N-1,1);
W3T = repmat(index1.',1,N-1);
W4T = repmat(index2.',1,N-1);

WuxxT1 = repmat((1./(1-x(ii).^2)),N-1,1);
WuxxT2 = repmat(x(ii)./(1-x(ii).^2).^(3/2),N-1,1);
WuyyT1 = repmat(1./(1-y(ii).^2),1,N-1);
WuyyT2 = repmat(y(ii)./(1-y(ii).^2).^(3/2),1,N-1);

% Start time-stepping
n = 0;

while n &lt; Nsteps
    [vv,vvold] = stepsolution(vv,vvold,ii,N,dt,W1T,W2T,W3T,W4T,...
                                 WuxxT1,WuxxT2,WuyyT1,WuyyT2);
    n = n + 1;
end


% Gather vvg back from GPU memory when done
vvg = gather(vv);


</pre><h3>Comparing CPU and GPU Execution Speeds<a name="24"></a></h3>
   <p>We ran a benchmark in which we measured the amount of time it took to execute 50 time steps for grid sizes of 64, 128, 512,
      1024, and 2048 on an Intel Xeon Processor X5650 and then using an NVIDIA Tesla C2050 GPU.
   </p>
   <p><img vspace="5" hspace="5" src="http://blogs.mathworks.com/images/loren/346/Benchmark.png"> </p>
   <p>For a grid size of 2048, the algorithm shows a 7.5x decrease in compute time from more than a minute on the CPU to less than
      10 seconds on the GPU.  The log scale plot shows that the CPU is actually faster for small grid sizes. As the technology evolves
      and matures, however, GPU solutions are increasingly able to handle smaller problems, a trend that we expect to continue.
   </p>
   <h3>Other Ways to Use the GPU with MATLAB<a name="27"></a></h3>
   <p>To accelerate an algorithm with multiple element-wise operations on a GPU, you can use <tt>arrayfun</tt>, which applies a function to each element of an GPUarray. Additionally if you have your own CUDA code, you can use the CUDAKernel
      interface to integrate this code with MATLAB.
   </p>
   <p>Ben Tordoff's previous guest blog post <a href="http://blogs.mathworks.com/loren/2011/07/18/a-mandelbrot-set-on-the-gpu/">Mandelbrots Sets on the GPU</a> shows a great example using both of these capabilities.
   </p>
     <p><em>Addendum</em>: There has been some confusion about using <tt>assignin</tt> and
<tt>evalin</tt> inside the body of <tt>parfor</tt> loops.  You can use these
functions if they use the 'base' workspace. However, please use caution
when using them since the 'base' workspace  will not be the same as the
client 'base' workspace.
   </p>   <h3>Your Thoughts?<a name="28"></a></h3>
   <p>Have you experimented with our new GPU functionality?  Let us know what you think or if you have any questions by leaving
      a comment for this post <a href="http://blogs.mathworks.com/loren/?p=346#respond">here</a>.
   </p><script language="JavaScript">
<!--

    function grabCode_43a6565ff583451ea3dcbf9a94261aab() {
        // 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='43a6565ff583451ea3dcbf9a94261aab ' + '##### ' + 'SOURCE BEGIN' + ' #####';
        t2='##### ' + 'SOURCE END' + ' #####' + ' 43a6565ff583451ea3dcbf9a94261aab';
    
        b=document.getElementsByTagName('body')[0];
        i1=b.innerHTML.indexOf(t1)+t1.length;
        i2=b.innerHTML.indexOf(t2);
 
        code_string = b.innerHTML.substring(i1, i2);
        code_string = code_string.replace(/REPLACE_WITH_DASH_DASH/g,'--');

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

        author = 'Sarah Wait Zaranek';
        copyright = 'Copyright 2012 The MathWorks, Inc.';

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

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

        d.write('</pre>\n');
      
      d.title = title + ' (MATLAB code)';
      d.close();
      }   
      
-->
</script><p style="text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray"><br /><a href="javascript:grabCode_43a6565ff583451ea3dcbf9a94261aab()"><span style="font-size: x-small;        font-style: italic;">Get 
            the MATLAB code 
            <noscript>(requires JavaScript)</noscript></span></a><br /><br />
      Published with MATLAB&reg; 7.13<br /></p>
</div>
<!--
43a6565ff583451ea3dcbf9a94261aab ##### SOURCE BEGIN #####
%% Using GPUs in MATLAB
% Today Iâ€™d like to introduce guest blogger
% <mailto:sarah.zaranek@mathworks.com Sarah Wait Zaranek> who works for the
% MATLAB Marketing team. Sarah previously has
% <http://blogs.mathworks.com/loren/2008/06/25/speeding-up-matlab-applications/
% written> about speeding up code from a customer to get acceptable
% performance. She will be discussing how to use GPUs to
% accelerate your MATLAB applications.

%% Overview  
% In this post, we first will introduce the basics of using the GPU with
% MATLAB and then move onto solving a 2nd-order wave equation using this
% GPU functionality. This blog post is inspired by a recent MATLAB Digest
% <http://www.mathworks.com/company/newsletters/articles/gpu-programming-in-matlab.html
% article> on GPU Computing that I coauthored with one of our developers,
% Jill Reese. Since the original demo was made, the GPU functions available
% in MATLAB have grown. If you compare the code below to the code in the
% paper- they are slightly different, reflecting these new capabilites.
% Additionally, small changes were made to enable easier explanation of the
% code in this blog format. The GPU functionality shown in this
% post requires the Parallel Computing Toolbox.
%
%% GPU Background
% Originally used to accelerate graphics rendering, GPUs are now
% increasingly applied to scientific calculations. Unlike a traditional
% CPU, which includes no more than a handful of cores, a GPU has a
% massively parallel array of integer and floating-point processors, as
% well as dedicated, high-speed memory. A typical GPU comprises hundreds of
% these smaller processors.  These processors can be used to greatly
% speed-up particular types of applications.
%
% A good rule of thumb is that your problem may be a good fit for the GPU
% if it is:
%%
% * Massively parallel: 
% The computations can be broken down into hundreds or thousands of
% independent units of work.  You will see the best performance when all of
% the cores are kept busy, exploiting the inherent parallel nature of the
% GPU. Seemingly simple, vectorized MATLAB calculations on arrays with 
% hundreds of thousands of elements often can fit into this category. 
%%
% * Computationally intensive: 
% The time spent on computation significantly exceeds the time spent on
% transferring data to and from GPU memory. Because a GPU is attached to
% the host CPU via the PCI Express bus, the memory access is slower than
% with a traditional CPU. This means that your overall computational
% speedup is limited by the amount of data transfer that occurs in your
% algorithm.
%
% Applications that do not satisfy these criteria might actually run more
% slowly on a GPU than on a CPU.

%% Learning About Our GPU
% With that background, we can now start working with the GPU in MATLAB.
% Let's start first by querying our GPU to see just what we are working
% with:

gpuDevice

%%
% We are running on a Tesla C2050.  Currently, Parallel Computing Toolbox
% supports NVDIA GPUs with Compute Capability 1.3 or greater. <http://www.nvidia.com/object/cuda_gpus.html
% Here> is a link to see if your card is supported. 

%% A Simple Example using Overloaded Functions 
% Over 100 operations (e.g. |fft|, |ifft|, |eig|) are now available as
% built-in MATLAB functions that can be executed directly on the GPU by
% providing an input argument of the type GPUArray. These GPU-enabled
% functions are overloadedâ€”in other words, they operate differently
% depending on the data type of the arguments passed to them.
% <http://www.mathworks.com/help/releases/R2011b/toolbox/distcomp/bsic4fr-1.html
% Here> is a list of all the overloaded functions.
%
% Let's create a GPUArray and perform a |fft| using the GPU. However,
% let's first do this on the CPU so that we can see the difference in code
% and performance

A1 = rand(3000,3000); 
tic;
B1 = fft(A1);
time1 = toc;

%%
% To perform the same operation on the GPU, we first use |gpuArray|
% to transfer data from the MATLAB workspace to device memory. Then
% we can run |fft|, which is one of the overloaded functions on that data:

A2 = gpuArray(A1); 
tic;
B2 = fft(A2);
time2 = toc;

%%
% The second case is executed on the GPU rather than the CPU since its
% input (a GPUArray) is held on the GPU. The result, |B2|, is stored on the 
% GPU. However, it is still visible in the MATLAB workspace. By running 
% |class(B2)|, we can see that it is also a GPUArray.

class(B2)

%%
% To bring the data back to the CPU, we run |gather|.

B2 = gather(B2);
class(B2)

%%
% |B2| is now on the CPU and has a class of double. 

%% Speedup For Our Simple Example
%
% In this simple example, we can calculate the speedup of performing the
% |fft| on our data.  
%
speedUp = time1/time2;
disp(speedUp)

%%
% It looks like our |fft| is running ~3.5x faster on the GPU. This is
% pretty good, especially since |fft| is multi-threaded in core MATLAB.
% However, to perform a realistic comparison, we should really include the
% time spent transferring the vector to and from the GPU. If we do that
% - we find that our acceleration is greatly reduced. Let's see what
% happens if we include the time to do our data transfer.

tic;
A3 = gpuArray(A1); 
B3 = fft(A3);
B3 = gather(B3);
time3 = toc;

speedUp = time1/time3;
disp(speedUp)

%% Understanding and Limiting Your Data Transfer Overhead 
%
% Data transfer overhead can become so significant that it degrades the
% application's overall performance, especially if you repeatedly exchange
% data between the CPU and GPU to execute relatively few computationally
% intensive operations. However not all hope is lost!  By limiting the data
% transfer between the GPU and the CPU, we can still acheive speedup.
%
% Instead of creating the data on the CPU and transferring it to the GPU -
% we can just create on the GPU directly.  There are several 
% <http://www.mathworks.com/help/releases/R2011b/toolbox/distcomp/bsic4fr-1.html
% constructors> available as well as constructor-like functions such as |meshgrid|.
% Let's see how that effects our time.  To be accurate, we should also
% retime the original serial code including the time it takes to generate
% the random matrix on the CPU.

tic;
A4 = rand(3000,3000); 
B4 = fft(A4);
time4 = toc;

tic;
A5 = parallel.gpu.GPUArray.rand(3000,3000); 
B5 = fft(A5);
B5 = gather(B5);
time5 = toc;

speedUp = time4/time5;
disp(speedUp);

%%
% This is better, although we still do see the influence of gathering the
% data back from the GPU.  In this simple demo, the effect is exaggerated
% because we are running a single, already fast operation on the GPU. It is
% more efficient to perform several operations on the data while it is on
% the GPU, bringing the data back to the CPU only when required. 

%% Solving the Wave Equation 
% <<WaveEquation.gif>>
%%
% To put the above example into context, let's use the same GPU
% functionality on a more "real-world" problem. To do this,  we are going
% to solve a second-order wave equation:
%%
% $$ \frac{\partial u}{\partial t} =  \frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2} $$

%%
% The algorithm we use to solve the wave equation combines a spectral
% method in space and a second-order central finite differenc method in
% time. Specifically, we apply the Chebyshev spectral method, which uses
% Chebyshev polynomials as the basis functions. Our example is largely
% based on an example in Trefethen's book:
% <http://www.mathworks.com/support/books/book48110.html "Spectral Methods
% in MATLAB">
%
%% Code Changes to Run Algorithm on GPU
% When accelerating our alogrithm, we focus on speeding up the code within
% the main time stepping while-loop. The operations in that part of the
% code (e.g. |fft| and |ifft|, matrix multiplication) are all overloaded
% functions that work with the GPU. As a result, we do not need to change
% the algorithm in any way to execute it on a GPU. We get to simply
% transfer the data to the GPU and back to the CPU when finished.

type('stepSolution.m')

%% Code Changes to Transfer Data to the GPU and Back Again
% The variables |dt|, |x|, |index1|, and |index2| are
% calculated on the CPU and transferred over to the GPU using |gpuArray|.
%
% For example:

N = 256;  
index1 = 1i*[0:N-1 0 1-N:-1];

index1 = gpuArray(index1);

%%
% For the rest of the variables, we create them directly on the GPU using
% the overloaded versions of the transpose operator (|'|), |repmat| ,and
% |meshgrid|. 
%
% For example:

W1T = repmat(index1,N-1,1);

%%
% When, we are done with all our calculations on the GPU, we use |gather|
% once to bring data back from the GPU. Note, that we don't have to
% transfer our data back to the CPU between time steps. This all comes
% together to look like this:

type WaveGPU.m

%% Comparing CPU and GPU Execution Speeds
% We ran a benchmark in which we measured the amount of time it took to
% execute 50 time steps for grid sizes of 64, 128, 512, 1024, and 2048 on
% an Intel Xeon Processor X5650 and then using an NVIDIA Tesla C2050 GPU.
%
%%
% <<Benchmark.png>>

%% 
% For a grid size of 2048, the algorithm shows a 7.5x decrease in compute
% time from more than a minute on the CPU to less than 10 seconds on the
% GPU.  The log scale plot shows that the CPU is actually faster
% for small grid sizes. As the technology evolves and matures, however, GPU
% solutions are increasingly able to handle smaller problems, a trend that
% we expect to continue.
% 
%% Other Ways to Use the GPU with MATLAB 
% To accelerate an algorithm with multiple element-wise operations on a
% GPU, you can use |arrayfun|, which applies a function to each element of
% an GPUarray. Additionally if you have your own CUDA code, you can use the
% CUDAKernel interface to integrate this code with MATLAB.
% 
% Ben Tordoff's previous guest blog post
% <http://blogs.mathworks.com/loren/2011/07/18/a-mandelbrot-set-on-the-gpu/
% Mandelbrots Sets on the GPU> shows a great example using both of these
% capabilities.

%% Your Thoughts?
% Have you experimented with our new GPU functionality?  Let us know what
% you think or if you have any questions by leaving a comment for this
% post <http://blogs.mathworks.com/loren/?p=346#respond here>.

##### SOURCE END ##### 43a6565ff583451ea3dcbf9a94261aab
-->
<img src="http://feeds.feedburner.com/~r/mathworks/loren/~4/ouvhwaD6oEY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.mathworks.com/loren/2012/02/06/using-gpus-in-matlab/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://blogs.mathworks.com/loren/2012/02/06/using-gpus-in-matlab/</feedburner:origLink></item>
	</channel>
</rss>

