Skip to content

Instantly share code, notes, and snippets.

@brazilbean
Last active December 20, 2015 21:19
Show Gist options
  • Save brazilbean/6197045 to your computer and use it in GitHub Desktop.
Save brazilbean/6197045 to your computer and use it in GitHub Desktop.
Functional Programming in Matlab - Declaring variables in anonymous functions
% Consider the scenario where you want to declare
% an anonymous function to do some task, but it
% requires multiple uses of a result that is
% expensive to compute.
% For example, consider the following series of statements:
a = rand(1000);
b = rand(1000);
c = a * b;
[a./c b./c]
% Let's say you want to encapsulate this procedure as an
% anonymous function of 'a' and 'b':
fun = @(a,b) [a./(a*b) b./(a*b)]
% This can be done by replacing 'c' with its definition.
% But if this definition is expensive to compute, you'd
% rather compute it once and reuse the results.
% Enter the 'apply' function:
apply = @(varargin) varargin{end}(varargin{1:end-1});
% Apply takes a series of arguments and passes them to
% the final argument. For example:
apply(1, 2, @(x, y) x + y)
% Returns 1 + 2 = 3
% This is useful in a functional programming context because
% it lets us declare secondary variables in an anonymous
% function:
fun = @(a,b) apply( a * b, @(c) [a./c b./c] )
% Now we have an anonymous function of two variables that
% performs a computation, captures the output, and uses
% the output in additional computations.
% Go team!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment