{"id":515,"date":"2012-08-29T08:56:49","date_gmt":"2012-08-29T13:56:49","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=515"},"modified":"2012-08-29T08:56:49","modified_gmt":"2012-08-29T13:56:49","slug":"thoughts-about-anonymous-functions","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2012\/08\/29\/thoughts-about-anonymous-functions\/","title":{"rendered":"Thoughts about Anonymous Functions"},"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>One of the reasons I like using anonymous functions is because they allow me to express whatever function I want to use as a function of the relevant arguments in different contexts.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#0e71bf4f-f70f-4cc3-9254-6eca08387dd2\">Example<\/a><\/li><li><a href=\"#3cf01852-c4e8-4489-87de-008c3c22dbda\">Choose a Particular Line to Plot<\/a><\/li><li><a href=\"#5f7cd995-35b3-425f-8492-ca187cbd72df\">Plot the Line<\/a><\/li><li><a href=\"#56088811-4c8f-4183-b399-17f33729a7ad\">Find Area Under the Line<\/a><\/li><li><a href=\"#aa6753ae-7948-4823-b3aa-8d44828b8b84\">Find Best Fit Line<\/a><\/li><li><a href=\"#d7b70c25-00cc-47ba-b47a-99d1a6788c6b\">Anonymous Functions Allow Interface Flexibility<\/a><\/li><li><a href=\"#e81442a1-c727-4fc2-965b-95064e758bb2\">Have You Used Anonymous Functions to Alter the Interface?<\/a><\/li><\/ul><\/div><h4>Example<a name=\"0e71bf4f-f70f-4cc3-9254-6eca08387dd2\"><\/a><\/h4><p>Here's a very general way I can write the code meant to generate points on a straight line.<\/p><pre class=\"codeinput\">straightline = @(X,slope,intercept) slope*X + intercept\r\n<\/pre><pre class=\"codeoutput\">straightline = \r\n    @(X,slope,intercept)slope*X+intercept\r\n<\/pre><h4>Choose a Particular Line to Plot<a name=\"3cf01852-c4e8-4489-87de-008c3c22dbda\"><\/a><\/h4><p>First let's choose a particular straight line segment.  I start by defining the slope and intercept values.<\/p><pre class=\"codeinput\">m = 2;  <span class=\"comment\">% slope<\/span>\r\nb = -3; <span class=\"comment\">% intercept<\/span>\r\n<\/pre><h4>Plot the Line<a name=\"5f7cd995-35b3-425f-8492-ca187cbd72df\"><\/a><\/h4><p>Now I can evaluate my function when I create the plot.<\/p><pre class=\"codeinput\">x = 2:0.1:5;\r\nplot(x,straightline(x,m,b))\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2012\/optionalInAnon1_01.png\" alt=\"\"> <h4>Find Area Under the Line<a name=\"56088811-4c8f-4183-b399-17f33729a7ad\"><\/a><\/h4><p>Now let's find the area under a segment of this line, between two points. Since the function <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/integral.html\"><tt>integral<\/tt><\/a> requires the integrand to be a function of one variable only, we can use the anonymous function <tt>myline<\/tt>, defined below, to create just such a representation.<\/p><pre class=\"codeinput\">lowerlimit = 2;\r\nupperlimit = 5;\r\n<\/pre><p>Create a function representing my particular line segment, by fixing those slope and intercept values, and creating a new function from the original one.<\/p><pre class=\"codeinput\">myline = @(x) straightline(x,m,b);\r\n<\/pre><p>Use this new function, <tt>myline<\/tt>, as the integrand.<\/p><pre class=\"codeinput\">myarea = integral(myline, lowerlimit, upperlimit)\r\n<\/pre><pre class=\"codeoutput\">myarea =\r\n    12\r\n<\/pre><h4>Find Best Fit Line<a name=\"aa6753ae-7948-4823-b3aa-8d44828b8b84\"><\/a><\/h4><p>Now suppose we have data, based on this line segment, that has some noise.  And we would like to estimate the slope and intercept values.<\/p><pre class=\"codeinput\">m = 2;\r\nb = -2;\r\nt = (2:0.2:5)';\r\ndata = straightline(t,m,b) + 0.2*randn(size(t));\r\nplot(t,data,<span class=\"string\">'m*'<\/span>)\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2012\/optionalInAnon1_02.png\" alt=\"\"> <p>Now I want slope and intercept to be my independent variables. I can use <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/polyfit.html\"><tt>polyfit<\/tt><\/a>.  Of course, I could use <tt>\\<\/tt> as well.<\/p><pre class=\"codeinput\">p = polyfit(t,data,1);\r\n<\/pre><p>Now compare estimates for slope and intercept to original values.<\/p><pre class=\"codeinput\">comparison = [m, b; p]\r\n<\/pre><pre class=\"codeoutput\">comparison =\r\n            2           -2\r\n        2.094      -2.3638\r\n<\/pre><p>Perhaps I instead want a function of the slope and intercept only.  In that case, with data supplied, I can derive such a function from <tt>straightline<\/tt>.  I can even get the values put into a<\/p><pre class=\"codeinput\">slopeIntercept = @(slope,intercept) straightline(data, slope, intercept);\r\nslp = [1 4]; intcpt = [0 -5];\r\nnewline1 = @(X) straightline(X, slp(1), intcpt(1));\r\nnewline2 = @(X) straightline(X, slp(2), intcpt(2));\r\n<\/pre><h4>Anonymous Functions Allow Interface Flexibility<a name=\"d7b70c25-00cc-47ba-b47a-99d1a6788c6b\"><\/a><\/h4><p>Using the same original function definition for <tt>straightline<\/tt>, I am able to mold the function for different purposes.  In the first case, I turned my function of 3 variables into a function of one variable, with preset parameters. I could also use it to create a function of just slope and intercept, suitable for create line segments for different parameters at a later time.<\/p><p>In fact, if I was trying to use my <tt>straightline<\/tt> function with some other code that required lines to be defined by slope and intercept first, and then the abscissa, I can easily create a new interface for the line.<\/p><pre class=\"codeinput\">differentLine = @(slope, intercept, X) straightline(X, slope, intercept);\r\n<\/pre><h4>Have You Used Anonymous Functions to Alter the Interface?<a name=\"e81442a1-c727-4fc2-965b-95064e758bb2\"><\/a><\/h4><p>I'd love to hear your thoughts <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=515#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_2a10fa4f62bc496e9ad5992eb2ecad62() {\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='2a10fa4f62bc496e9ad5992eb2ecad62 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 2a10fa4f62bc496e9ad5992eb2ecad62';\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 2012 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_2a10fa4f62bc496e9ad5992eb2ecad62()\"><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; 7.14<br><\/p><p class=\"footer\"><br>\r\n      Published with MATLAB&reg; 7.14<br><\/p><\/div><!--\r\n2a10fa4f62bc496e9ad5992eb2ecad62 ##### SOURCE BEGIN #####\r\n%% Thoughts about Anonymous Functions\r\n% One of the reasons I like using anonymous functions is because they allow\r\n% me to express whatever function I want to use as a function of the\r\n% relevant arguments in different contexts.  \r\n%% Example\r\n% Here's a very general way I can write the code meant to generate points\r\n% on a straight line.\r\nstraightline = @(X,slope,intercept) slope*X + intercept\r\n%% Choose a Particular Line to Plot\r\n% First let's choose a particular straight line segment.  I start by\r\n% defining the slope and intercept values.  \r\nm = 2;  % slope\r\nb = -3; % intercept\r\n%% Plot the Line\r\n% Now I can evaluate my function when I create the plot.\r\nx = 2:0.1:5;\r\nplot(x,straightline(x,m,b))\r\n%% Find Area Under the Line\r\n% Now let's find the area under a segment of this line, between two points.\r\n% Since the function\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/integral.html |integral|>\r\n% requires the integrand to be a function of one variable only, we can use\r\n% the anonymous function |myline|, defined below, to create just such a\r\n% representation.\r\nlowerlimit = 2;\r\nupperlimit = 5;\r\n%%\r\n% Create a function representing my particular line segment, by fixing\r\n% those slope and intercept values, and creating a new function from the\r\n% original one.\r\nmyline = @(x) straightline(x,m,b);\r\n%% \r\n% Use this new function, |myline|, as the integrand.\r\nmyarea = integral(myline, lowerlimit, upperlimit)\r\n%% Find Best Fit Line\r\n% Now suppose we have data, based on this line segment, that has some\r\n% noise.  And we would like to estimate the slope and intercept values.\r\nm = 2; \r\nb = -2;\r\nt = (2:0.2:5)';\r\ndata = straightline(t,m,b) + 0.2*randn(size(t));\r\nplot(t,data,'m*')\r\n%%\r\n% Now I want slope and intercept to be my independent variables. I can use\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/polyfit.html |polyfit|>.  Of\r\n% course, I could use |\\| as well.\r\np = polyfit(t,data,1);\r\n%%\r\n% Now compare estimates for slope and intercept to original values.\r\ncomparison = [m, b; p]\r\n%% \r\n% Perhaps I instead want a function of the slope and intercept only.  In\r\n% that case, with data supplied, I can derive such a function from\r\n% |straightline|.  I can even get the values put into a\r\nslopeIntercept = @(slope,intercept) straightline(data, slope, intercept);\r\nslp = [1 4]; intcpt = [0 -5];\r\nnewline1 = @(X) straightline(X, slp(1), intcpt(1));\r\nnewline2 = @(X) straightline(X, slp(2), intcpt(2));\r\n%% Anonymous Functions Allow Interface Flexibility\r\n% Using the same original function definition for |straightline|, I am able\r\n% to mold the function for different purposes.  In the first case, I turned\r\n% my function of 3 variables into a function of one variable, with preset\r\n% parameters. I could also use it to create a function of just slope and\r\n% intercept, suitable for create line segments for different parameters at\r\n% a later time.\r\n%\r\n% In fact, if I was trying to use my |straightline| function with some\r\n% other code that required lines to be defined by slope and intercept\r\n% first, and then the abscissa, I can easily create a new interface for the\r\n% line.\r\ndifferentLine = @(slope, intercept, X) straightline(X, slope, intercept);\r\n%% Have You Used Anonymous Functions to Alter the Interface?\r\n% I'd love to hear your thoughts\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=515#respond here>.\r\n\r\n\r\n\r\n\r\n\r\n##### SOURCE END ##### 2a10fa4f62bc496e9ad5992eb2ecad62\r\n-->","protected":false},"excerpt":{"rendered":"<!--introduction--><p>One of the reasons I like using anonymous functions is because they allow me to express whatever function I want to use as a function of the relevant arguments in different contexts.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2012\/08\/29\/thoughts-about-anonymous-functions\/\">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,39],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/515"}],"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=515"}],"version-history":[{"count":4,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/515\/revisions"}],"predecessor-version":[{"id":519,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/515\/revisions\/519"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=515"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=515"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=515"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}