{"id":626,"date":"2013-02-07T07:18:56","date_gmt":"2013-02-07T12:18:56","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=626"},"modified":"2013-02-14T07:37:09","modified_gmt":"2013-02-14T12:37:09","slug":"introduction-to-functional-programming-with-anonymous-functions-part-3","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2013\/02\/07\/introduction-to-functional-programming-with-anonymous-functions-part-3\/","title":{"rendered":"Introduction to Functional Programming with Anonymous Functions, Part 3"},"content":{"rendered":"<!DOCTYPE html\r\n  PUBLIC \"-\/\/W3C\/\/DTD HTML 4.01 Transitional\/\/EN\">\r\n<style type=\"text\/css\">\r\n\r\nh1 { font-size:18pt; }\r\nh2.titlebg { font-size:13pt; }\r\nh3 { color:#4A4F55; padding:0px; margin:5px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:11pt; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }\r\nh4 { color:#4A4F55; padding:0px; margin:0px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:10pt; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }\r\n   \r\np { padding:0px; margin:0px 0px 20px; }\r\nimg { padding:0px; margin:0px 0px 20px; border:none; }\r\np img, pre img, tt img, li img { margin-bottom:0px; } \r\n\r\nul { padding:0px; margin:0px 0px 20px 23px; list-style:square; }\r\nul li { padding:0px; margin:0px 0px 7px 0px; background:none; }\r\nul li ul { padding:5px 0px 0px; margin:0px 0px 7px 23px; }\r\nul li ol li { list-style:decimal; }\r\nol { padding:0px; margin:0px 0px 20px 0px; list-style:decimal; }\r\nol li { padding:0px; margin:0px 0px 7px 23px; list-style-type:decimal; }\r\nol li ol { padding:5px 0px 0px; margin:0px 0px 7px 0px; }\r\nol li ol li { list-style-type:lower-alpha; }\r\nol li ul { padding-top:7px; }\r\nol li ul li { list-style:square; }\r\n\r\npre, tt, code { font-size:12px; }\r\npre { margin:0px 0px 20px; }\r\npre.error { color:red; }\r\npre.codeinput { padding:10px; border:1px solid #d3d3d3; background:#f7f7f7; }\r\npre.codeoutput { padding:10px 11px; margin:0px 0px 20px; color:#4c4c4c; }\r\n\r\n@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }\r\n\r\nspan.keyword { color:#0000FF }\r\nspan.comment { color:#228B22 }\r\nspan.string { color:#A020F0 }\r\nspan.untermstring { color:#B20000 }\r\nspan.syscmd { color:#B28C00 }\r\n\r\n.footer { width:auto; padding:10px 0px; margin:25px 0px 0px; border-top:1px dotted #878787; font-size:0.8em; line-height:140%; font-style:italic; color:#878787; text-align:left; float:none; }\r\n.footer p { margin:0px; }\r\n\r\n  <\/style><div class=\"content\"><!--introduction--><p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/225094\">Tucker McClure<\/a> is an Application Engineer with The MathWorks. He spends his time helping our customers accelerate their work with the right tools and problem-solving techniques. Today, he'll be discussing how \"functional programming\" can help create brief and powerful MATLAB code.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#fbd7e3ee-92ff-43b6-81f3-57ddc9c1bad8\">Recap<\/a><\/li><li><a href=\"#d67c1251-5092-46c4-92d2-ec90d91b397a\">Loops<\/a><\/li><li><a href=\"#15f6ff53-2e88-4c45-a182-587c356829ce\">Loops via Recursion<\/a><\/li><li><a href=\"#17158a9d-0555-43db-8ec1-940e1db24e27\">A Better Loop<\/a><\/li><li><a href=\"#cd7045ed-4b59-43a8-83ee-864e517f18d3\">Doing More in a Loop<\/a><\/li><li><a href=\"#0ac5b619-0410-4f86-8707-136803bc052d\">Final Example<\/a><\/li><li><a href=\"#557636cc-ac2e-4883-ac9d-ef26209d702e\">Summary<\/a><\/li><\/ul><\/div><h4>Recap<a name=\"fbd7e3ee-92ff-43b6-81f3-57ddc9c1bad8\"><\/a><\/h4><p>For Part 1, click <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=607\">here<\/a>. For Part 2, click <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=611\">here<\/a>.<\/p><p>When we left off, we had implemented conditional statements, recursion, and multi-line statements in anonymous functions, so today we'll tackle loops.<\/p><p>Before we get started, let's implement the functions that we'll need again.<\/p><pre class=\"codeinput\">iif     = @(varargin) varargin{2*find([varargin{1:2:end}], 1, <span class=\"string\">'first'<\/span>)}();\r\nrecur   = @(f, varargin) f(f, varargin{:});\r\ncurly   = @(x, varargin) x{varargin{:}};\r\n<\/pre><h4>Loops<a name=\"d67c1251-5092-46c4-92d2-ec90d91b397a\"><\/a><\/h4><p>Note that the recursive sequences we created in the last part could also have been implemented with <tt>for<\/tt> loops. For instance, here's factorial of <tt>n<\/tt>:<\/p><pre>   factorial = 1;\r\n   for k = 1:n\r\n       factorial = k * factorial;\r\n   end<\/pre><p>Many times, recursive functions can be written iteratively in loops. However, we can't use <tt>for<\/tt> or <tt>while<\/tt> in an anonymous function, so instead of asking how we can unwrap recursive functions into iterative loops, let's ask the reverse: how can we implement loops with recursive functions?<\/p><h4>Loops via Recursion<a name=\"15f6ff53-2e88-4c45-a182-587c356829ce\"><\/a><\/h4><p>To loop properly, one must know:<\/p><div><ul><li>What to do each iteration<\/li><li>If the process should continue to the next iteration<\/li><li>What's available when the loop begins<\/li><\/ul><\/div><p>Allowing the \"what to do\" to be a function (<tt>fcn<\/tt>) of some state (<tt>x<\/tt>), the \"if it should continue\" to be another function (<tt>cont<\/tt>) of the state, and \"what's available when the loop begins\" to be the initial state (<tt>x0<\/tt>), we can write a <tt>loop<\/tt> function. This is a big step, so bear with me for some explanation!<\/p><p>On each step, the loop function will call the <tt>cont<\/tt> function, passing in all elements of the state, <tt>x<\/tt>, as in <tt>cont(x{:})<\/tt>. If that returns false (meaning we shouldn't continue), the current state, <tt>x<\/tt>, is returned. Otherwise, if we <i>should<\/i> continue, it calls <tt>fcn<\/tt> with all elements of the current state, as in <tt>fcn(x{:})<\/tt>, and passes the output from that to the next iteration. Letting this single iteration be denoted as <tt>f<\/tt>, we can build the anonymous function <tt>loop<\/tt> using our <tt>recur<\/tt> function.<\/p><pre class=\"codeinput\">loop = @(x0, cont, fcn) <span class=\"keyword\">...<\/span><span class=\"comment\">                                     % Header<\/span>\r\n       recur(@(f, x) iif(~cont(x{:}), x, <span class=\"keyword\">...<\/span><span class=\"comment\">                    % Continue?<\/span>\r\n                         true,        @() f(f, fcn(x{:}))), <span class=\"keyword\">...<\/span><span class=\"comment\"> %   Iterate<\/span>\r\n             x0);                                               <span class=\"comment\">% from x0.<\/span>\r\n<\/pre><p>For this trivial example, the state is simply the iteration count. We'll increase the count every iteration until the count <tt>&gt;= n<\/tt> and return the final count. All this does therefore is count from 0 to the input <tt>n<\/tt>. Not very interesting, but it demonstrates the loop.<\/p><pre class=\"codeinput\">count = @(n) loop({0}, <span class=\"keyword\">...<\/span><span class=\"comment\">          % Initialize state, k, to 0<\/span>\r\n                  @(k) k &lt; n, <span class=\"keyword\">...<\/span><span class=\"comment\">   % While k &lt; n<\/span>\r\n                  @(k) {k + 1});    <span class=\"comment\">%   k = k + 1 (returned as cell array)<\/span>\r\n\r\narrayfun(count, 1:10)\r\n<\/pre><pre class=\"codeoutput\">ans = \r\n    [1]    [2]    [3]    [4]    [5]    [6]    [7]    [8]    [9]    [10]\r\n<\/pre><p>I suppose that worked, but why are we using cell arrays to store the state, such as <tt>{0}<\/tt> and <tt>{k+1}<\/tt>? There are two reasons. First, if <tt>x<\/tt> is a cell array, then when we dump all elements of <tt>x<\/tt> into <tt>fcn<\/tt>, they become multiple arguments! That is, <tt>fcn(x{:})<\/tt> is the same as <tt>fcn(x{1}, x{2}, ...)<\/tt>. So instead of our function taking a big cell array for an input, it can take named arguments, which we'll use below. Second, we do this because it allows a function to <i>return<\/i> multiple elements that will be used by the next iteration, so if a function needed to return <tt>y<\/tt> and <tt>z<\/tt>, which would be arguments to the next iteration, it can simply return one cell array, <tt>{y, z}<\/tt>. It makes it easy to use. Here's a factorial example demonstrating this. The state is two different things: the iteration count, <tt>k<\/tt>, and factorial of the previous number, <tt>x<\/tt>. Note that both values of the state, <tt>k<\/tt> and <tt>x<\/tt>, are inputs to all of the functions. Note here how we're using <tt>@(k, x)<\/tt> for our functions. By allowing <tt>x<\/tt> to be a cell array, each element of the array becomes an argument such as <tt>k<\/tt> or <tt>x<\/tt>!<\/p><pre class=\"codeinput\">factorial = @(n) loop({1, 1}, <span class=\"keyword\">...<\/span><span class=\"comment\">          % Start with k = 1 and x = 1<\/span>\r\n                      @(k, x) k &lt;= n, <span class=\"keyword\">...<\/span><span class=\"comment\">  % While k &lt;= n<\/span>\r\n                      @(k, x) {k + 1, <span class=\"keyword\">...<\/span><span class=\"comment\">  %   k = k + 1;<\/span>\r\n                               k * x});    <span class=\"comment\">%   x = k * x;<\/span>\r\n<\/pre><p>Call it:<\/p><pre class=\"codeinput\">factorial(5)\r\n<\/pre><pre class=\"codeoutput\">ans = \r\n    [6]    [120]\r\n<\/pre><p>Wait, we wanted 120 (the fifth number of the factorial sequence), so what's that 6 doing there?<\/p><h4>A Better Loop<a name=\"17158a9d-0555-43db-8ec1-940e1db24e27\"><\/a><\/h4><p>Remember how we return the full state? That's not very useful for this factorial example, as we get both <tt>k<\/tt> and the number we want as outputs in that cell array. Because the whole state isn't generally useful, let's add a <tt>cleanup<\/tt> function to our loop. We'll execute this when the loop is done (right after <tt>~cont(...)<\/tt> returns <tt>false<\/tt>). Our <tt>cleanup<\/tt> function will take the full state and return only the important parts.<\/p><pre class=\"codeinput\">loop = @(x0, cont, fcn, cleanup) <span class=\"keyword\">...<\/span><span class=\"comment\">                            % Header<\/span>\r\n       recur(@(f, x) iif(~cont(x{:}), cleanup(x{:}), <span class=\"keyword\">...<\/span><span class=\"comment\">        % Continue?<\/span>\r\n                         true,        @() f(f, fcn(x{:}))), <span class=\"keyword\">...<\/span><span class=\"comment\"> %   Iterate<\/span>\r\n             x0);                                               <span class=\"comment\">% from x0.<\/span>\r\n<\/pre><p>Now here's factorial, with clean output.<\/p><pre class=\"codeinput\">factorial = @(n) loop({1, 1}, <span class=\"keyword\">...<\/span><span class=\"comment\">         % Start with k = 1 and x = 1<\/span>\r\n                      @(k,x) k &lt;= n, <span class=\"keyword\">...<\/span><span class=\"comment\">  % While k &lt;= n<\/span>\r\n                      @(k,x) {k + 1, <span class=\"keyword\">...<\/span><span class=\"comment\">  %   k = k + 1;<\/span>\r\n                              k * x}, <span class=\"keyword\">...<\/span><span class=\"comment\"> %   x = k * x;<\/span>\r\n                      @(k,x) x);          <span class=\"comment\">% End, returning x<\/span>\r\n<\/pre><p>The result:<\/p><pre class=\"codeinput\">factorial(5)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n   120\r\n<\/pre><p>First seven numbers of factorial:<\/p><pre class=\"codeinput\">arrayfun(factorial, 1:7)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n  Columns 1 through 6\r\n           1           2           6          24         120         720\r\n  Column 7\r\n        5040\r\n<\/pre><p>That's better.<\/p><p>I'll be the first to admit that the loop is a bit longer and much more rigid than a normal MATLAB loop. On the other hand, it can be used in anonymous functions, and its syntax has a certain cleanliness to it in that it doesn't modify any variables that live outside the loop; it has its own scope. This is one nice feature of <tt>loop<\/tt> being a <i>function<\/i> that takes <i>code<\/i> (functions) as arguments.<\/p><h4>Doing More in a Loop<a name=\"cd7045ed-4b59-43a8-83ee-864e517f18d3\"><\/a><\/h4><p>Let's say we want to do something else in the loop, but don't want its output passed to the next iteration, like printing something out. Remember the <tt>do_three_things<\/tt> example from last time? We executed numerous statements by putting them in a cell array and used <tt>curly<\/tt> to access the output we cared about. We can do that here, in a loop. For example, let's write out a function to print <tt>n<\/tt> digits of the factorial sequence. We'll use an array to store two things. The first will be the number that <tt>fprintf<\/tt> returns, which we don't care about. The second will be the cell array we want to return, <tt>k<\/tt> and <tt>x<\/tt>. We'll access that cell array with <tt>curly<\/tt>, as in <tt>curly({..., {k, x}}, 2)<\/tt>, which just returns <tt>{k, x}<\/tt>.<\/p><pre class=\"codeinput\">say_it = @(k, x) fprintf(<span class=\"string\">'Factorial(%d): %d\\n'<\/span>, k, x);\r\nprint_factorial = @(n) loop({1, 1}, <span class=\"keyword\">...<\/span><span class=\"comment\">               % Start with k=1, x=1<\/span>\r\n                      @(k,x) k &lt;= n, <span class=\"keyword\">...<\/span><span class=\"comment\">              % While k &lt;= n<\/span>\r\n                      @(k,x) curly({say_it(k,k*x),<span class=\"keyword\">...<\/span><span class=\"comment\"> % Print, discard<\/span>\r\n                                    {k + 1, <span class=\"keyword\">...<\/span><span class=\"comment\">       %   k = k + 1;<\/span>\r\n                                     k * x}}, <span class=\"keyword\">...<\/span><span class=\"comment\">     %   x = k * x;<\/span>\r\n                                   2), <span class=\"keyword\">...<\/span><span class=\"comment\">            %   Return {k+1,k*x}.<\/span>\r\n                      @(k,x) x);                      <span class=\"comment\">% End, returning x<\/span>\r\n<\/pre><pre class=\"codeinput\">print_factorial(7);\r\n<\/pre><pre class=\"codeoutput\">Factorial(1): 1\r\nFactorial(2): 2\r\nFactorial(3): 6\r\nFactorial(4): 24\r\nFactorial(5): 120\r\nFactorial(6): 720\r\nFactorial(7): 5040\r\n<\/pre><p>Now we're executing multiple things and only returning what we want while inside a loop built built on recursion and anonymous conditionals! We've come a long way since Part 1.<\/p><p>As a practical note, recall that because these loops use recursion, there's a limit to the number of times they can loop (MATLAB has a recursion limit, which is a setting in Preferences). Also, a recursive implementation of a loop isn't the most efficient. For this reason, it's best to implement <tt>loop<\/tt> itself in a file that can then be used in the same way. If it's in a file, it can also be kept on the MATLAB path so that it can be used anywhere.<\/p><pre>   function x = loop(x, cont, f, cleanup)\r\n       while cont(x{:})\r\n           x = f(x{:});\r\n       end\r\n       if nargin == 4\r\n           x = cleanup(x{:});\r\n       end\r\n   end<\/pre><h4>Final Example<a name=\"0ac5b619-0410-4f86-8707-136803bc052d\"><\/a><\/h4><p>This brings us to our final example. Below, we'll simulate a simple <a href=\"http:\/\/en.wikipedia.org\/wiki\/Harmonic_oscillator\">harmonic oscillator<\/a> over time, using a structure to store dissimilar states, including a complete time history of the oscillator. This might simulate, for example, the sway of a lamp that's hanging from the ceiling after an earthquake.<\/p><pre class=\"codeinput\"><span class=\"comment\">% First, calculate a state transition matrix that represents a harmonic<\/span>\r\n<span class=\"comment\">% oscillator with damping. Multiplying this by |x| produces |x| at a<\/span>\r\n<span class=\"comment\">% slightly later time. The math here isn't important to the example.<\/span>\r\nPhi = expm(0.5*[0 1; -1 -0.2]);\r\n\r\n<span class=\"comment\">% Now create the loop.<\/span>\r\nx   = loop({[1; 0], 1}, <span class=\"keyword\">...<\/span><span class=\"comment\">                  % Initial state, x = [1; 0]<\/span>\r\n           @(x,k) k &lt;= 100, <span class=\"keyword\">...<\/span><span class=\"comment\">              % While k &lt;= 100<\/span>\r\n           @(x,k) {[x, Phi * x(:, end)], <span class=\"keyword\">...<\/span><span class=\"comment\"> %   Update x<\/span>\r\n                   k + 1}, <span class=\"keyword\">...<\/span><span class=\"comment\">               %   Update k<\/span>\r\n           @(x,k) x);                        <span class=\"comment\">% End, return x<\/span>\r\n\r\n<span class=\"comment\">% Create a plot function.<\/span>\r\nplot_it = @(n, x, y, t) {subplot(2, 1, n), <span class=\"keyword\">...<\/span><span class=\"comment\">            % Select subplot.<\/span>\r\n                         plot(x(n, :)), <span class=\"keyword\">...<\/span><span class=\"comment\">               % Plot the data.<\/span>\r\n                         iif(nargin==4, @() title(t), <span class=\"keyword\">...<\/span><span class=\"comment\"> % If there's a<\/span>\r\n                             true,      []), <span class=\"keyword\">...<\/span><span class=\"comment\">          % title, add it.<\/span>\r\n                         ylabel(y), <span class=\"keyword\">...<\/span><span class=\"comment\">                   % Label y<\/span>\r\n                         xlabel(<span class=\"string\">'Time (s)'<\/span>)};             <span class=\"comment\">% and x axes.<\/span>\r\n\r\n<span class=\"comment\">% Plot the result.<\/span>\r\nplot_it(1, x, <span class=\"string\">'Position (m)'<\/span>, <span class=\"string\">'Harmonic Oscillator'<\/span>);\r\nplot_it(2, x, <span class=\"string\">'Velocity (m\/s)'<\/span>);\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2013\/functional_programming_techniques_3_01.png\" alt=\"\"> <h4>Summary<a name=\"557636cc-ac2e-4883-ac9d-ef26209d702e\"><\/a><\/h4><p>That's it for loops via recursion!<\/p><p>Let's look back at what we did over these three parts. First, we started with a simple <tt>map<\/tt> utility function to demonstrate the function-of-functions idea. Then we created our ubiquitous inline if, which further enabled recursion (a conditional is necessary to make recursion stop!). We also showed using multiple statements by storing their outputs in a cell array. Finally, we created a <tt>loop<\/tt> construct on top of our recursion functions.<\/p><p>At this point, we've done more than just scratch the surface of functional programming. We've used MATLAB's interesting constructs, such as function handles, cell arrays, and <tt>varargin<\/tt> to implement a functional programming framework, allowing a new syntax within MATLAB, where code can be arguments to flow control functions. Here's a roundup of what we created.<\/p><pre class=\"codeinput\">map   = @(val, fcns) cellfun(@(f) f(val{:}), fcns);\r\nmapc  = @(val, fcns) cellfun(@(f) f(val{:}), fcns, <span class=\"string\">'UniformOutput'<\/span>, 0);\r\niif   = @(varargin) varargin{2*find([varargin{1:2:end}], 1, <span class=\"string\">'first'<\/span>)}();\r\nrecur = @(f, varargin) f(f, varargin{:});\r\nparen = @(x, varargin) x(varargin{:});\r\ncurly = @(x, varargin) x{varargin{:}};\r\nloop  = @(x0,c,f,r)recur(@(g,x)iif(c(x{:}),@()g(g,f(x{:})),1,r(x{:})),x0);\r\n<\/pre><p>These have also been programmed as \"normal\" MATLAB functions so that they can be kept on the path and used whenever they're needed. These can be found under \"Functional Programming Constructs\" in File Exchange, <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/39735-functional-programming-constructs\">here<\/a>.<\/p><p>Thanks for reading. I hope this has both enabled a new level of detail in anonymous functions in MATLAB and helped demonstrate the wide range of possibilities available within the MATLAB language.<\/p><p>Do you have other functional programming patterns you use in your code? For instance, a do-while loop is just like our loop above except that it always runs at least one iteration. Any ideas how to program this or other interesting constructs in anonymous functions? Please let us know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=626#respond\">here<\/a>!<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_fee28ac6c0854f4d8c4456a6d8df6e0c() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='fee28ac6c0854f4d8c4456a6d8df6e0c ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' fee28ac6c0854f4d8c4456a6d8df6e0c';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        copyright = 'Copyright 2013 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n\r\n        d.title = title + ' (MATLAB code)';\r\n        d.close();\r\n    }   \r\n     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_fee28ac6c0854f4d8c4456a6d8df6e0c()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2012b<br><\/p><p class=\"footer\"><br>\r\n      Published with MATLAB&reg; R2012b<br><\/p><\/div><!--\r\nfee28ac6c0854f4d8c4456a6d8df6e0c ##### SOURCE BEGIN #####\r\n%% Introduction to Functional Programming with Anonymous Functions, Part 3\r\n%\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/225094 \r\n% Tucker McClure> is an Application Engineer with The MathWorks. He spends\r\n% his time helping our customers accelerate their work with the right tools\r\n% and problem-solving techniques. Today, he'll be discussing how\r\n% \"functional programming\" can help create brief and powerful MATLAB code.\r\n\r\n%% Recap\r\n% For Part 1, click <https:\/\/blogs.mathworks.com\/loren\/?p=607 here>.\r\n% For Part 2, click <https:\/\/blogs.mathworks.com\/loren\/?p=611 here>.\r\n%\r\n% When we left off, we had implemented conditional statements, recursion,\r\n% and multi-line statements in anonymous functions, so today we'll tackle \r\n% loops.\r\n% \r\n% Before we get started, let's implement the functions that we'll need \r\n% again.\r\n\r\niif     = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();\r\nrecur   = @(f, varargin) f(f, varargin{:});\r\ncurly   = @(x, varargin) x{varargin{:}};\r\n\r\n%% Loops\r\n%\r\n% Note that the recursive sequences we created in the last part could also\r\n% have been implemented with |for| loops. For instance, here's factorial \r\n% of |n|:\r\n% \r\n%     factorial = 1;\r\n%     for k = 1:n\r\n%         factorial = k * factorial;\r\n%     end\r\n% \r\n% Many times, recursive functions can be written iteratively in loops.\r\n% However, we can't use |for| or |while| in an anonymous function, so \r\n% instead of asking how we can unwrap recursive functions into iterative \r\n% loops, let's ask the reverse: how can we implement loops with recursive \r\n% functions?\r\n\r\n%% Loops via Recursion\r\n%\r\n% To loop properly, one must know:\r\n% \r\n% * What to do each iteration\r\n% * If the process should continue to the next iteration\r\n% * What's available when the loop begins\r\n% \r\n% Allowing the \"what to do\" to be a function (|fcn|) of some state (|x|),\r\n% the \"if it should continue\" to be another function (|cont|) of the state,\r\n% and \"what's available when the loop begins\" to be the initial state \r\n% (|x0|), we can write a |loop| function. This is a big step, so bear with\r\n% me for some explanation!\r\n%\r\n% On each step, the loop function will call the |cont| function, passing in\r\n% all elements of the state, |x|, as in |cont(x{:})|. If that returns false\r\n% (meaning we shouldn't continue), the current state, |x|, is returned.\r\n% Otherwise, if we _should_ continue, it calls |fcn| with all elements of \r\n% the current state, as in |fcn(x{:})|, and passes the output from that to\r\n% the next iteration. Letting this single iteration be denoted as |f|, we\r\n% can build the anonymous function |loop| using our |recur| function.\r\n\r\nloop = @(x0, cont, fcn) ...                                     % Header\r\n       recur(@(f, x) iif(~cont(x{:}), x, ...                    % Continue?\r\n                         true,        @() f(f, fcn(x{:}))), ... %   Iterate\r\n             x0);                                               % from x0.\r\n\r\n%%\r\n% For this trivial example, the state is simply the iteration count. We'll\r\n% increase the count every iteration until the count |>= n| and return the\r\n% final count. All this does therefore is count from 0 to the input |n|.\r\n% Not very interesting, but it demonstrates the loop.\r\n\r\ncount = @(n) loop({0}, ...          % Initialize state, k, to 0\r\n                  @(k) k < n, ...   % While k < n\r\n                  @(k) {k + 1});    %   k = k + 1 (returned as cell array)\r\n\r\narrayfun(count, 1:10)\r\n\r\n%%\r\n% I suppose that worked, but why are we using cell arrays to store the \r\n% state, such as |{0}| and |{k+1}|? There are two reasons. First, if |x| is\r\n% a cell array, then when we dump all elements of |x| into |fcn|, they \r\n% become multiple arguments! That is, |fcn(x{:})| is the same as \r\n% |fcn(x{1}, x{2}, ...)|. So instead of our function taking a big cell array for an input, it can take named \r\n% arguments, which we'll use below. Second, we do this because it allows a function to _return_ \r\n% multiple elements that will be used by the next iteration, so if a \r\n% function needed to return |y| and |z|, which would be arguments to the \r\n% next iteration, it can simply return one cell array, |{y, z}|. It makes \r\n% it easy to use. Here's a factorial example demonstrating this. The state \r\n% is two different things: the iteration count, |k|, and factorial of the \r\n% previous number, |x|. Note that both values of the state, |k| and |x|, \r\n% are inputs to all of the functions. Note here how we're using |@(k, x)|\r\n% for our functions. By allowing |x| to be a cell array, each element of\r\n% the array becomes an argument such as |k| or |x|!\r\n\r\nfactorial = @(n) loop({1, 1}, ...          % Start with k = 1 and x = 1\r\n                      @(k, x) k <= n, ...  % While k <= n\r\n                      @(k, x) {k + 1, ...  %   k = k + 1;\r\n                               k * x});    %   x = k * x;\r\n\r\n%%\r\n% Call it:\r\n\r\nfactorial(5)\r\n\r\n%%\r\n% Wait, we wanted 120 (the fifth number of the factorial sequence), so\r\n% what's that 6 doing there?\r\n\r\n%% A Better Loop\r\n% Remember how we return the full state? That's not very useful for this\r\n% factorial example, as we get both |k| and the number we want as outputs\r\n% in that cell array. Because the whole state isn't generally useful, let's\r\n% add a |cleanup| function to our loop. We'll execute this when the loop is\r\n% done (right after |~cont(...)| returns |false|). Our |cleanup| function\r\n% will take the full state and return only the important parts.\r\n\r\nloop = @(x0, cont, fcn, cleanup) ...                            % Header\r\n       recur(@(f, x) iif(~cont(x{:}), cleanup(x{:}), ...        % Continue?\r\n                         true,        @() f(f, fcn(x{:}))), ... %   Iterate\r\n             x0);                                               % from x0.\r\n\r\n%%\r\n% Now here's factorial, with clean output.\r\n\r\nfactorial = @(n) loop({1, 1}, ...         % Start with k = 1 and x = 1\r\n                      @(k,x) k <= n, ...  % While k <= n\r\n                      @(k,x) {k + 1, ...  %   k = k + 1;\r\n                              k * x}, ... %   x = k * x;\r\n                      @(k,x) x);          % End, returning x\r\n\r\n%%\r\n% The result:\r\nfactorial(5)\r\n\r\n%%\r\n% First seven numbers of factorial:\r\n\r\narrayfun(factorial, 1:7)\r\n\r\n%%\r\n% That's better.\r\n%\r\n% I'll be the first to admit that the loop is a bit longer and much more \r\n% rigid than a normal MATLAB loop. On the other hand, it can be used in\r\n% anonymous functions, and its syntax has a certain cleanliness to it in\r\n% that it doesn't modify any variables that live outside the loop; it has\r\n% its own scope. This is one nice feature of |loop| being a _function_ that\r\n% takes _code_ (functions) as arguments.\r\n\r\n%% Doing More in a Loop\r\n% Let's say we want to do something else in the loop, but don't want its\r\n% output passed to the next iteration, like printing something out.\r\n% Remember the |do_three_things| example from last time? We executed\r\n% numerous statements by putting them in a cell array and used |curly| to\r\n% access the output we cared about. We can do that here, in a loop. For\r\n% example, let's write out a function to print |n| digits of the factorial\r\n% sequence. We'll use an array to store two things. The first will be the\r\n% number that |fprintf| returns, which we don't care about. The second will\r\n% be the cell array we want to return, |k| and |x|. We'll access that cell\r\n% array with |curly|, as in |curly({..., {k, x}}, 2)|, which just\r\n% returns |{k, x}|.\r\n\r\nsay_it = @(k, x) fprintf('Factorial(%d): %d\\n', k, x);\r\nprint_factorial = @(n) loop({1, 1}, ...               % Start with k=1, x=1\r\n                      @(k,x) k <= n, ...              % While k <= n\r\n                      @(k,x) curly({say_it(k,k*x),... % Print, discard\r\n                                    {k + 1, ...       %   k = k + 1;\r\n                                     k * x}}, ...     %   x = k * x;\r\n                                   2), ...            %   Return {k+1,k*x}.\r\n                      @(k,x) x);                      % End, returning x\r\n\r\n%%\r\nprint_factorial(7);\r\n\r\n%%\r\n% Now we're executing multiple things and only returning what we want while\r\n% inside a loop built built on recursion and anonymous conditionals! We've\r\n% come a long way since Part 1.\r\n\r\n%%\r\n% As a practical note, recall that because these loops use recursion,\r\n% there's a limit to the number of times they can loop (MATLAB has a\r\n% recursion limit, which is a setting in Preferences). Also, a recursive\r\n% implementation of a loop isn't the most efficient. For this reason, it's\r\n% best to implement |loop| itself in a file that can then be used in the\r\n% same way. If it's in a file, it can also be kept on the MATLAB path so \r\n% that it can be used anywhere.\r\n% \r\n%     function x = loop(x, cont, f, cleanup)\r\n%         while cont(x{:})\r\n%             x = f(x{:});\r\n%         end\r\n%         if nargin == 4\r\n%             x = cleanup(x{:});\r\n%         end\r\n%     end\r\n         \r\n%% Final Example\r\n% This brings us to our final example. Below, we'll simulate a simple\r\n% <http:\/\/en.wikipedia.org\/wiki\/Harmonic_oscillator harmonic oscillator>\r\n% over time, using a structure to store dissimilar states, including a \r\n% complete time history of the oscillator. This might simulate, for \r\n% example, the sway of a lamp that's hanging from the ceiling after an \r\n% earthquake.\r\n\r\n% First, calculate a state transition matrix that represents a harmonic\r\n% oscillator with damping. Multiplying this by |x| produces |x| at a \r\n% slightly later time. The math here isn't important to the example.\r\nPhi = expm(0.5*[0 1; -1 -0.2]);\r\n\r\n% Now create the loop.\r\nx   = loop({[1; 0], 1}, ...                  % Initial state, x = [1; 0]\r\n           @(x,k) k <= 100, ...              % While k <= 100\r\n           @(x,k) {[x, Phi * x(:, end)], ... %   Update x\r\n                   k + 1}, ...               %   Update k\r\n           @(x,k) x);                        % End, return x\r\n\r\n% Create a plot function.\r\nplot_it = @(n, x, y, t) {subplot(2, 1, n), ...            % Select subplot.\r\n                         plot(x(n, :)), ...               % Plot the data.\r\n                         iif(nargin==4, @() title(t), ... % If there's a\r\n                             true,      []), ...          % title, add it.\r\n                         ylabel(y), ...                   % Label y\r\n                         xlabel('Time (s)')};             % and x axes.\r\n\r\n% Plot the result.\r\nplot_it(1, x, 'Position (m)', 'Harmonic Oscillator');\r\nplot_it(2, x, 'Velocity (m\/s)');\r\n\r\n%% Summary\r\n% That's it for loops via recursion! \r\n%\r\n% Let's look back at what we did over these three parts. First, we started\r\n% with a simple |map| utility function to demonstrate the\r\n% function-of-functions idea. Then we created our ubiquitous inline if,\r\n% which further enabled recursion (a conditional is necessary to make\r\n% recursion stop!). We also showed using multiple statements by storing\r\n% their outputs in a cell array. Finally, we created a |loop| construct on \r\n% top of our recursion functions.\r\n% \r\n% At this point, we've done more than just scratch the surface of \r\n% functional programming. We've used MATLAB's interesting constructs, such \r\n% as function handles, cell arrays, and |varargin| to implement a \r\n% functional programming framework, allowing a new syntax within MATLAB,\r\n% where code can be arguments to flow control functions. Here's a roundup\r\n% of what we created.\r\n\r\nmap   = @(val, fcns) cellfun(@(f) f(val{:}), fcns);\r\nmapc  = @(val, fcns) cellfun(@(f) f(val{:}), fcns, 'UniformOutput', 0);\r\niif   = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();\r\nrecur = @(f, varargin) f(f, varargin{:});\r\nparen = @(x, varargin) x(varargin{:});\r\ncurly = @(x, varargin) x{varargin{:}};\r\nloop  = @(x0,c,f,r)recur(@(g,x)iif(c(x{:}),@()g(g,f(x{:})),1,r(x{:})),x0);\r\n\r\n%%\r\n% These have also been programmed as \"normal\" MATLAB functions so that they\r\n% can be kept on the path and used whenever they're needed. These can be\r\n% found under \"Functional Programming Constructs\" in File Exchange, \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/39735-functional-programming-constructs\r\n% here>.\r\n%\r\n% Thanks for reading. I hope this has both enabled a new level of detail in\r\n% anonymous functions in MATLAB and helped demonstrate the wide range of\r\n% possibilities available within the MATLAB language.\r\n%\r\n% Do you have other functional programming patterns you use in your code? \r\n% For instance, a do-while loop is just like our loop above except that it\r\n% always runs at least one iteration. Any ideas how to program this or \r\n% other interesting constructs in anonymous functions? Please let us know \r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=626#respond here>!\r\n\r\n##### SOURCE END ##### fee28ac6c0854f4d8c4456a6d8df6e0c\r\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2013\/functional_programming_techniques_3_01.png\" onError=\"this.style.display ='none';\" \/><\/div><!--introduction--><p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/225094\">Tucker McClure<\/a> is an Application Engineer with The MathWorks. He spends his time helping our customers accelerate their work with the right tools and problem-solving techniques. Today, he'll be discussing how \"functional programming\" can help create brief and powerful MATLAB code.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2013\/02\/07\/introduction-to-functional-programming-with-anonymous-functions-part-3\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[3,54],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/626"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=626"}],"version-history":[{"count":6,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/626\/revisions"}],"predecessor-version":[{"id":634,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/626\/revisions\/634"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=626"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=626"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=626"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}