Search⌘ K

Lambda Functions

Explore how to define and apply lambda functions in both Python and MATLAB environments. This lesson helps you understand anonymous functions, their syntax differences, and practical uses such as filtering lists and applying functions to arrays, providing a foundation for efficient coding with inline functions.

A lambda function is an anonymous function in Python and MATLAB. It is often used when we only need to use a function in one place because we can define the function inline without giving it a name.

Anonymous function in MATLAB

In MATLAB, we can define a lambda function using the @ symbol followed by a list of arguments in parentheses () and a line of code. A lambda function returns the value of the line of code. Here’s an example of a lambda function in MATLAB that takes one argument and returns its square.

C
% Declaring an anonymous function
my_square_function = @(n) n.^2;
%% Call "my_square_func" function
number = 7;
number_sq = my_square_function(number);
%% Display results
fprintf('Square of %1.0f is %1.0f',number,number_sq);

Lambda function in Python

In Python, we can define a lambda function using the lambda keyword, followed by a list of arguments, a colon (:), and the function body. A lambda function returns the value of the expression after the colon. Here’s an example of a lambda function ...