Q1 = create_quadratic_function( 1, 1, 1) Now we can create new quadratic functions and use them just as normal MATLAB Of anonymous functions only when it is clear and concise.
Parameters, you may need to use the syntax of nested functions. However, when you need to perform complex operation with respect to the The syntax of anonymous functions: create_quadratic_function = a*x.^ 2 + b*x + c Qf = you are an one-linear, you can also define the above function using function qf = create_quadratic_function (a, b, c) function y = quadratic_function (x) It will create a new quadraticįunction with every set of new coefficients. TheĮxample below shows a quadratic function factory. Basically, you create a function that works likeĪ factory that creates new functions depending on the input parameters. In addition to the above example, there are many other neat applications that Take a look at the followingĬode and you will get a better idea: f = x.*x % just a simple quadratic function That maps functions with their scaled versions. Operator (here I mean the operator in mathematics, not computer programming)
Interestingly, the above code implements a simple scale You may wonder why it bothers to write such "confusing" code to make a function G = you call the returned function, it will access the local variables f and In MATLAB, if you write the some code similar to the code below, you createĪ closure: function g = scale_operator (f, scale) % Here we assume f has a single return value, and scale is also a scalar function y = scaled_function (varargin) % Note that we use the local variable scale and f here, which is within % the scope of scale_operator(). Persistent local variable scope, which usually occurs when yourįunction A returns a function B that references local variables in function A. (I mean the closures in computer programming, not mathematics) in MATLAB, Provide great flexibility when coding in MATLAB.