{"id":607,"date":"2013-01-10T14:54:30","date_gmt":"2013-01-10T19:54:30","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=607"},"modified":"2013-01-10T07:16:38","modified_gmt":"2013-01-10T12:16:38","slug":"introduction-to-functional-programming-with-anonymous-functions-part-1","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2013\/01\/10\/introduction-to-functional-programming-with-anonymous-functions-part-1\/","title":{"rendered":"Introduction to Functional Programming with Anonymous Functions, Part 1"},"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=\"#0e44c07b-d367-4463-8569-84c5584677cf\">The Goal<\/a><\/li><li><a href=\"#ac0bd6ff-b525-44e5-bceb-708f1b5ef735\">Minimum and Maximum Example<\/a><\/li><li><a href=\"#105b3d75-0e67-4142-b1a1-69ae20036a6f\">Map<\/a><\/li><li><a href=\"#c8d04efb-1a2d-4c35-afff-dd52e6c660d2\">Inline Conditionals<\/a><\/li><li><a href=\"#f74979be-981d-4cce-b0b4-1c129dcd9b1a\">To Be Continued<\/a><\/li><\/ul><\/div><h4>The Goal<a name=\"0e44c07b-d367-4463-8569-84c5584677cf\"><\/a><\/h4><p>I use a lot of anonymous functions. They're nice and compact and almost invisible in their simplicity. Plus, if I can write an anonymous function to do something, I don't need to save the function in a file, and that can save me from file clutter on larger projects and from having to send someone a dozen files instead of sending one clean script. However, it seems at first glance like anonymous functions must necessarily be simple. No <tt>if... else<\/tt>, <tt>while<\/tt>, <tt>for<\/tt>, or any other keywords can be used. So how could we possibly write sophisticated programs in anonymous functions? We'll see, and it will involve some ideas from functional programming.<\/p><p>The goal of this introduction is to demonstrate how a few of these techniques can change the way we work in MATLAB, allowing greater brevity and simultaneously increasing readability. There are three parts. In this first part, we'll present creating functions of functions and treating functions as variables (in MATLAB, that means function handles), and from there, we'll move on to implementing conditional statements (like <tt>if... else<\/tt>) in anonymous functions. In the next part, we'll add recursion and executing multiple statements inside an anonymous function. In the final part, we'll develop a loop function. But first, if \"function handle\" or \"anonymous function\" is new to you, go check out Loren&#8217;s great introductions to those ideas in her <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/function-handles\/\">previous posts<\/a>!<\/p><h4>Minimum and Maximum Example<a name=\"ac0bd6ff-b525-44e5-bceb-708f1b5ef735\"><\/a><\/h4><p>Let's say we want to write a function to find the minimum and maximum of a set of numbers and store the results in an array. Here's a first pass:<\/p><pre class=\"codeinput\">min_and_max = @(x) [min(x), max(x)];\r\nmin_and_max([3 4 1 6 2])\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     1     6\r\n<\/pre><p>Our <tt>min_and_max<\/tt> function takes in an array that we'll call <tt>x<\/tt>, finds the minimum and maximum, and stores the two results in an output array. Clear? Good. But now let's make it more difficult. The <tt>min<\/tt> and <tt>max<\/tt> functions both return <b>two<\/b> outputs if desired (both the minimum or maximum <i>and<\/i> the index at which they occur in the input array). Our simple <tt>min_and_max<\/tt> function can't get those secondary outputs! How can we access them? Consider this odd-looking line.<\/p><pre class=\"codeinput\">[extrema, indices] = cellfun(@(f) f([3 4 1 6 2]), {@min, @max})\r\n<\/pre><pre class=\"codeoutput\">extrema =\r\n     1     6\r\nindices =\r\n     3     4\r\n<\/pre><p>Well, that clearly worked. The minimum, 1, occurs at index 3. The maximum, 6, occurs at index 4, but what is this line actually doing? First, recall how <tt><a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/cellfun.html\">cellfun<\/a><\/tt> behaves. The first argument is a <i>function handle<\/i>. The second argument is a cell array of whatever. Each element of the cell array is given as an argument to the provided function handle. Most of the time, that cell array is full of data, and each piece of data is passed to the function. However, we could just as easily put function handles in the cell array. Then the first function (<tt>@(f) f(...)<\/tt>) <i>acts on all the other functions<\/i>. So, first <tt>@min<\/tt> is passed in for <tt>f<\/tt> and the outputs from <tt>min([3 4 1 6 2])<\/tt> are stored. Then, <tt>@max<\/tt> is passed in for <tt>f<\/tt>, and its outputs are stored.<\/p><p>Ok, now that we're working with functions of functions, let's remove that hard-coded <tt>[3 4 1 6 2]<\/tt> and write a new <tt>min_and_max<\/tt> function by simply adding a <tt>@(x)<\/tt> out front and changing <tt>[3 4 1 6 2]<\/tt> to <tt>x<\/tt>.<\/p><pre class=\"codeinput\">min_and_max = @(x) cellfun(@(f) f(x), {@min, @max});\r\n<\/pre><p>We can now use <tt>min_and_max<\/tt> for just the extrema, like before, but we can also get the indices too.<\/p><pre class=\"codeinput\">y = randi(10, 1, 10)\r\njust_values        = min_and_max(y)\r\n[~, just_indices]  = min_and_max(y)\r\n[extrema, indices] = min_and_max(y)\r\n<\/pre><pre class=\"codeoutput\">y =\r\n     2    10    10     5     9     2     5    10     8    10\r\njust_values =\r\n     2    10\r\njust_indices =\r\n     1     2\r\nextrema =\r\n     2    10\r\nindices =\r\n     1     2\r\n<\/pre><p>That might have looked a little funny, but it's pretty easy to think about, right? Now let's make it look a little nicer too.<\/p><h4>Map<a name=\"105b3d75-0e67-4142-b1a1-69ae20036a6f\"><\/a><\/h4><p>Above, we're mapping each function to our input <tt>x<\/tt>. More generally, we might write a \"map\" function to map a series of functions to the input values. We'll make <tt>val<\/tt> a cell array so we can also send multiple inputs to multiple functions all at once. This is like what we had before, but rearranged a bit.<\/p><pre class=\"codeinput\">map = @(val, fcns) cellfun(@(f) f(val{:}), fcns);\r\n<\/pre><p>Look how simple this makes <tt>min_and_max<\/tt> (below), while still accessing both outputs. Not only is it shorter to write than any other versions so far, it's easier to read, with hardly anything but a single occurrence of each variable or function name. \"Map <tt>x<\/tt> to the <tt>min<\/tt> and <tt>max<\/tt> functions\". No problem.<\/p><pre class=\"codeinput\">x = [3 4 1 6 2];\r\n[extrema, indices] = map({x}, {@min, @max})\r\n<\/pre><pre class=\"codeoutput\">extrema =\r\n     1     6\r\nindices =\r\n     3     4\r\n<\/pre><p>Let's try multiple inputs:<\/p><pre class=\"codeinput\">map({1, 2}, {@plus, @minus, @times})\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     3    -1     2\r\n<\/pre><p>What if outputs are different sizes? We'll write <tt>mapc<\/tt> (as in MAP with Cell array outputs) to handle this; all it needs is an extra argument to <tt>cellfun<\/tt> to say that our output isn't uniform in size.<\/p><pre class=\"codeinput\">mapc = @(val, fcns) cellfun(@(f) f(val{:}), fcns, <span class=\"string\">'UniformOutput'<\/span>, false);\r\n<\/pre><p>Send <tt>pi<\/tt> to multiple functions that return differently-sized arrays. The first output is a scalar, the second is a scalar, and the third is a string.<\/p><pre class=\"codeinput\">mapc({pi}, {@(x) 2 * x, <span class=\"keyword\">...<\/span><span class=\"comment\">                     % Multiply by 2<\/span>\r\n            @cos, <span class=\"keyword\">...<\/span><span class=\"comment\">                           % Find cosine<\/span>\r\n            @(x) sprintf(<span class=\"string\">'x is %.5f...'<\/span>, x)})   <span class=\"comment\">% Return a string<\/span>\r\n<\/pre><pre class=\"codeoutput\">ans = \r\n    [6.2832]    [-1]    'x is 3.14159...'\r\n<\/pre><p>That takes care of <tt>map<\/tt>, which we can now use anywhere to send a set of inputs to numerous functions and collect their multiple outputs with brief and easy-to-read code.<\/p><p>By the way, writing these <b>functions that operate on other functions<\/b> is part of the \"functional programming\" style, and we're just scratching the surface. Let's go a little deeper and see how we can write a function to choose which function to apply from a list of functions.<\/p><h4>Inline Conditionals<a name=\"c8d04efb-1a2d-4c35-afff-dd52e6c660d2\"><\/a><\/h4><p>Sometimes an anonymous function might need a condition, like <tt>if...else<\/tt>. However, normal MATLAB syntax doesn't allow program flow statements like these in anonymous functions. Hope it not lost. We can implement an \"inline if\" in a single line:<\/p><pre class=\"codeinput\">iif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, <span class=\"string\">'first'<\/span>)}();\r\n<\/pre><p>Alright, that looks decidedly strange, so before we discuss how it works, take a look at how easy it is to use:<\/p><pre>   [out1, out2, ...] = iif( if this,      then run this, ...\r\n                            else if this, then run this, ...\r\n                            ...\r\n                            else,         then run this );<\/pre><p>All the \"if this\" conditions should evaluate to true or false. The \"then run this\" action next to the first true condition is executed. None of the other actions are executed! We could use this to make, for example, a safe normalization function to do the following:<\/p><div><ul><li>If not all values of <tt>x<\/tt> are finite, throw an error.<\/li><li>Else if all values of <tt>x<\/tt> are equal to 0, return zeros.<\/li><li>Else, return <tt>x\/norm(x)<\/tt>.<\/li><\/ul><\/div><p>This is implemented below. Note the <tt>@()<\/tt> out in front of the actions. This means, \"don't do this action, but <i>refer<\/i> to this action\". That is, we're passing <i>pieces of code<\/i> to the <tt>iif<\/tt> function as <i>arguments<\/i>. In this way, we aren't actually doing all three things; we'll only call the action for the single case we need.<\/p><pre class=\"codeinput\">normalize = @(x) iif( ~all(isfinite(x)), @() error(<span class=\"string\">'Must be finite!'<\/span>), <span class=\"keyword\">...<\/span>\r\n                      all(x == 0),       @() zeros(size(x)), <span class=\"keyword\">...<\/span>\r\n                      true,              @() x\/norm(x) );\r\n<\/pre><p>Test the nominal condition.<\/p><pre class=\"codeinput\">normalize([1 1 0])\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n      0.70711      0.70711            0\r\n<\/pre><p>Test the error condition with non-finite inputs.<\/p><pre class=\"codeinput\"><span class=\"keyword\">try<\/span> normalize([0 inf 2]), <span class=\"keyword\">catch<\/span> err, disp(err.message); <span class=\"keyword\">end<\/span>\r\n<\/pre><pre class=\"codeoutput\">Must be finite!\r\n<\/pre><p>Test the all-zeros condition.<\/p><pre class=\"codeinput\">normalize([0 0 0])\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     0     0     0\r\n<\/pre><p>Easy to use, right? We've implemented <tt>if... else<\/tt> behavior without needing an actual <tt>if<\/tt> or <tt>else<\/tt> anywhere! So now it's time to see how this thing works.<\/p><p>First, the <tt>iif<\/tt> function takes any number of arguments, thanks to <tt>varargin<\/tt>. These arguments will be condition 1 (true or false), action 1 (a function), condition 2, action 2, etc. First, the <tt>iif<\/tt> function selects all of the conditions (that's the odd numbered items in <tt>varargin<\/tt>) via <tt>[varargin{1:2:end}]<\/tt>. For our safe norm, this returns:<\/p><pre>   [~all(isfinite(x)), all(x == 0), true]<\/pre><p>Next, it finds the index of the first <tt>true<\/tt> value in those conditions with <tt>find(..., 1, 'first')<\/tt>. E.g., if <tt>~all(isfinite(x))<\/tt> was <tt>false<\/tt>, but <tt>all(x == 0)<\/tt> was <tt>true<\/tt>, the index would be 2.<\/p><p>The actions to perform are the even-numbered items of <tt>varargin<\/tt>, so we just multiply that index by 2 to get the index of the action to perform. Finally, we execute the action by appending <tt>()<\/tt> on the end, as in<\/p><pre>   varargin{...}()<\/pre><p>Did you catch what was happening there? We're passing little pieces of <i>code<\/i> as <i>inputs<\/i> to the <tt>iif<\/tt> function. <i>Functions<\/i> as <i>arguments<\/i>. See why this is called \"functional\" programming? I'll admit it looks weird at first, but once you've seen it, the pattern is hard to forget.<\/p><p>Ok, that's it for today. Here are the functions we developed today.<\/p><pre class=\"codeinput\">iif  = @(varargin) varargin{2*find([varargin{1:2:end}], 1, <span class=\"string\">'first'<\/span>)}();\r\nmap  = @(val, fcns) cellfun(@(f) f(val{:}), fcns);\r\nmapc = @(val, fcns) cellfun(@(f) f(val{:}), fcns, <span class=\"string\">'UniformOutput'<\/span>, false);\r\n<\/pre><p>These can also be found <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/39735-functional-programming-constructs\">here<\/a>, implemented as regular MATLAB functions that can be kept on the path.<\/p><h4>To Be Continued<a name=\"f74979be-981d-4cce-b0b4-1c129dcd9b1a\"><\/a><\/h4><p>In the next installment, we'll build on these to enable recursion and to make anonymous functions that execute multiple statements. In the mean time, there are multiple ways to accomplish an inline if. For instance, I've seen a very brief ternary operator in our forums in the past. I'm curious what other implementations people might suggest for this type of behavior, so please post suggestions <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=607#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_3de19d6052724775bac735362e0fb5a5() {\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='3de19d6052724775bac735362e0fb5a5 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 3de19d6052724775bac735362e0fb5a5';\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_3de19d6052724775bac735362e0fb5a5()\"><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\n3de19d6052724775bac735362e0fb5a5 ##### SOURCE BEGIN #####\r\n%% Introduction to Functional Programming with Anonymous Functions, Part 1\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%% The Goal\r\n% I use a lot of anonymous functions. They're nice and compact and almost \r\n% invisible in their simplicity. Plus, if I can write an anonymous function\r\n% to do something, I don't need to save the function in a file, and that \r\n% can save me from file clutter on larger projects and from having to send \r\n% someone a dozen files instead of sending one clean script. However, it \r\n% seems at first glance like anonymous functions must necessarily be \r\n% simple. No |if... else|, |while|, |for|, or any other keywords can be \r\n% used. So how could we possibly write sophisticated programs in anonymous \r\n% functions? We'll see, and it will involve some ideas from functional \r\n% programming.\r\n%\r\n% The goal of this introduction is to demonstrate how a few of these\r\n% techniques can change the way we work in MATLAB, allowing greater brevity\r\n% and simultaneously increasing readability. There are three parts. In this\r\n% first part, we'll present creating functions of functions and treating\r\n% functions as variables (in MATLAB, that means function handles), and from\r\n% there, we'll move on to implementing conditional statements (like\r\n% |if... else|) in anonymous functions. In the next part, we'll add\r\n% recursion and executing multiple statements inside an anonymous function.\r\n% In the final part, we'll develop a loop function. But first, if \r\n% \"function handle\" or \"anonymous function\" is new to you, go check out \r\n% Loren\u00e2\u20ac\u2122s great introductions to those ideas in her \r\n% <https:\/\/blogs.mathworks.com\/loren\/category\/function-handles\/ \r\n% previous posts>!\r\n\r\n%% Minimum and Maximum Example\r\n% Let's say we want to write a function to find the minimum and maximum of\r\n% a set of numbers and store the results in an array. Here's a first pass:\r\n\r\nmin_and_max = @(x) [min(x), max(x)];\r\nmin_and_max([3 4 1 6 2])\r\n\r\n%%\r\n% Our |min_and_max| function takes in an array that we'll call |x|, finds\r\n% the minimum and maximum, and stores the two results in an output array.\r\n% Clear? Good. But now let's make it more difficult. The |min| and |max|\r\n% functions both return *two* outputs if desired (both the minimum or \r\n% maximum _and_ the index at which they occur in the input array). Our\r\n% simple |min_and_max| function can't get those secondary outputs! How can \r\n% we access them? Consider this odd-looking line.\r\n\r\n[extrema, indices] = cellfun(@(f) f([3 4 1 6 2]), {@min, @max})\r\n\r\n%%\r\n% Well, that clearly worked. The minimum, 1, occurs at index 3. The\r\n% maximum, 6, occurs at index 4, but what is this line actually doing?\r\n% First, recall how |<https:\/\/www.mathworks.com\/help\/matlab\/ref\/cellfun.html\r\n% cellfun>| behaves. The first argument is a _function handle_. The second \r\n% argument is a cell array of whatever. Each element of the cell array is \r\n% given as an argument to the provided function handle. Most of the time, \r\n% that cell array is full of data, and each piece of data is passed to the \r\n% function. However, we could just as easily put function handles in the \r\n% cell array. Then the first function (|@(f) f(...)|) _acts on all the \r\n% other functions_. So, first |@min| is passed in for |f| and the outputs \r\n% from |min([3 4 1 6 2])| are stored. Then, |@max| is passed in for |f|, \r\n% and its outputs are stored.\r\n%\r\n% Ok, now that we're working with functions of functions, let's remove that\r\n% hard-coded |[3 4 1 6 2]| and write a new |min_and_max| function by simply\r\n% adding a |@(x)| out front and changing |[3 4 1 6 2]| to |x|.\r\n\r\nmin_and_max = @(x) cellfun(@(f) f(x), {@min, @max});\r\n\r\n%%\r\n% We can now use |min_and_max| for just the extrema, like before, but we \r\n% can also get the indices too.\r\n\r\ny = randi(10, 1, 10)\r\njust_values        = min_and_max(y)\r\n[~, just_indices]  = min_and_max(y)\r\n[extrema, indices] = min_and_max(y)\r\n\r\n%%\r\n% That might have looked a little funny, but it's pretty easy to think\r\n% about, right? Now let's make it look a little nicer too.\r\n\r\n%% Map\r\n% Above, we're mapping each function to our input |x|. More generally, we\r\n% might write a \"map\" function to map a series of functions to the input\r\n% values. We'll make |val| a cell array so we can also send multiple inputs\r\n% to multiple functions all at once. This is like what we had before, but \r\n% rearranged a bit.\r\n\r\nmap = @(val, fcns) cellfun(@(f) f(val{:}), fcns);\r\n\r\n%%\r\n% Look how simple this makes |min_and_max| (below), while still accessing\r\n% both outputs. Not only is it shorter to write than any other versions so\r\n% far, it's easier to read, with hardly anything but a single occurrence of\r\n% each variable or function name. \"Map |x| to the |min| and |max| \r\n% functions\". No problem.\r\n\r\nx = [3 4 1 6 2];\r\n[extrema, indices] = map({x}, {@min, @max})\r\n\r\n%%\r\n% Let's try multiple inputs:\r\n\r\nmap({1, 2}, {@plus, @minus, @times})\r\n\r\n%%\r\n% What if outputs are different sizes? We'll write |mapc| (as in MAP with \r\n% Cell array outputs) to handle this; all it needs is an extra argument to \r\n% |cellfun| to say that our output isn't uniform in size.\r\n\r\nmapc = @(val, fcns) cellfun(@(f) f(val{:}), fcns, 'UniformOutput', false);\r\n\r\n%%\r\n% Send |pi| to multiple functions that return differently-sized arrays. The\r\n% first output is a scalar, the second is a scalar, and the third is a \r\n% string.\r\n\r\nmapc({pi}, {@(x) 2 * x, ...                     % Multiply by 2\r\n            @cos, ...                           % Find cosine\r\n            @(x) sprintf('x is %.5f...', x)})   % Return a string\r\n\r\n%%\r\n% That takes care of |map|, which we can now use anywhere to send a set of \r\n% inputs to numerous functions and collect their multiple outputs with\r\n% brief and easy-to-read code.\r\n%\r\n% By the way, writing these *functions that operate on other functions* is\r\n% part of the \"functional programming\" style, and we're just scratching the\r\n% surface. Let's go a little deeper and see how we can write a function to \r\n% choose which function to apply from a list of functions.\r\n\r\n%% Inline Conditionals\r\n% Sometimes an anonymous function might need a condition, like |if...else|.\r\n% However, normal MATLAB syntax doesn't allow program flow statements like\r\n% these in anonymous functions. Hope it not lost. We can implement an\r\n% \"inline if\" in a single line:\r\n\r\niif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, 'first')}();\r\n\r\n%%\r\n% Alright, that looks decidedly strange, so before we discuss how it works,\r\n% take a look at how easy it is to use:\r\n%\r\n%     [out1, out2, ...] = iif( if this,      then run this, ...\r\n%                              else if this, then run this, ...\r\n%                              ...\r\n%                              else,         then run this );\r\n%\r\n% All the \"if this\" conditions should evaluate to true or false. The \"then\r\n% run this\" action next to the first true condition is executed. None of\r\n% the other actions are executed! We could use this to make, for example, a\r\n% safe normalization function to do the following:\r\n%\r\n% * If not all values of |x| are finite, throw an error.\r\n% * Else if all values of |x| are equal to 0, return zeros.\r\n% * Else, return |x\/norm(x)|.\r\n%\r\n% This is implemented below. Note the |@()| out in front of the actions. \r\n% This means, \"don't do this action, but _refer_ to this action\". That is,\r\n% we're passing _pieces of code_ to the |iif| function as _arguments_. In\r\n% this way, we aren't actually doing all three things; we'll only call the\r\n% action for the single case we need.\r\n\r\nnormalize = @(x) iif( ~all(isfinite(x)), @() error('Must be finite!'), ...\r\n                      all(x == 0),       @() zeros(size(x)), ...\r\n                      true,              @() x\/norm(x) );\r\n                 \r\n%%\r\n% Test the nominal condition.\r\nnormalize([1 1 0])\r\n\r\n%%\r\n% Test the error condition with non-finite inputs.\r\ntry normalize([0 inf 2]), catch err, disp(err.message); end\r\n\r\n%%\r\n% Test the all-zeros condition.\r\nnormalize([0 0 0])\r\n\r\n%%\r\n% Easy to use, right? We've implemented |if... else| behavior without\r\n% needing an actual |if| or |else| anywhere! So now it's time to see how\r\n% this thing works.\r\n%\r\n% First, the |iif| function takes any number of arguments, thanks to\r\n% |varargin|. These arguments will be condition 1 (true or false), action 1\r\n% (a function), condition 2, action 2, etc. First, the |iif| function\r\n% selects all of the conditions (that's the odd numbered items in\r\n% |varargin|) via |[varargin{1:2:end}]|. For our safe norm, this returns:\r\n%\r\n%     [~all(isfinite(x)), all(x == 0), true]\r\n%\r\n% Next, it finds the index of the first |true| value in those conditions\r\n% with |find(..., 1, 'first')|. E.g., if |~all(isfinite(x))| was |false|,\r\n% but |all(x == 0)| was |true|, the index would be 2.\r\n%\r\n% The actions to perform are the even-numbered items of |varargin|, so we\r\n% just multiply that index by 2 to get the index of the action to perform.\r\n% Finally, we execute the action by appending |()| on the end, as in\r\n%\r\n%     varargin{...}()\r\n% \r\n% Did you catch what was happening there? We're passing little pieces of\r\n% _code_ as _inputs_ to the |iif| function. _Functions_ as _arguments_. \r\n% See why this is called \"functional\" programming? I'll admit it looks \r\n% weird at first, but once you've seen it, the pattern is hard to forget.\r\n%\r\n% Ok, that's it for today. Here are the functions we developed today.\r\n\r\niif  = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();\r\nmap  = @(val, fcns) cellfun(@(f) f(val{:}), fcns);\r\nmapc = @(val, fcns) cellfun(@(f) f(val{:}), fcns, 'UniformOutput', false);\r\n\r\n%%\r\n% These can also be found \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/39735-functional-programming-constructs here>,\r\n% implemented as regular MATLAB functions that can be kept on the path.\r\n\r\n%% To Be Continued\r\n% In the next installment, we'll build on these to enable recursion and to \r\n% make anonymous functions that execute multiple statements. In the mean \r\n% time, there are multiple ways to accomplish an inline if. For instance, \r\n% I've seen a very brief ternary operator in our forums in the past. I'm \r\n% curious what other implementations people might suggest for this type of \r\n% behavior, so please post suggestions \r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=607#respond here>.\r\n\r\n##### SOURCE END ##### 3de19d6052724775bac735362e0fb5a5\r\n-->","protected":false},"excerpt":{"rendered":"<!--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\/01\/10\/introduction-to-functional-programming-with-anonymous-functions-part-1\/\">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\/607"}],"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=607"}],"version-history":[{"count":4,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/607\/revisions"}],"predecessor-version":[{"id":624,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/607\/revisions\/624"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=607"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=607"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=607"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}