MATLAB Anonymous Functions

This chapter introduces Anonymous Functions in MATLAB, which are simple, one-line functions defined without the need for a separate .m file. Anonymous functions allow for quick calculations and functional programming techniques. They are particularly useful for small tasks or as inputs to functions like arrayfun or integral.

Chapter Goal

The goal of this chapter is to provide a thorough understanding of MATLAB anonymous functions, their syntax, and their applications. Key points include:

  1. Understanding the structure and use of anonymous functions.
  2. Exploring the use of anonymous functions with multiple inputs.
  3. Using anonymous functions as inputs to other MATLAB functions.
  4. Implementing best practices for anonymous functions.

Key Characteristics for MATLAB Anonymous Functions

  1. One-Line Definition: Anonymous functions are defined in a single line of code.
  2. No Separate File: Unlike regular functions, anonymous functions do not require a .m file.
  3. Flexible Inputs: They can accept multiple inputs and produce a single output.
  4. Scoped Variables: Anonymous functions can use variables from their parent workspace.
  5. Functional Programming: Commonly used as inputs to higher-order functions like arrayfun, cellfun, or integral.

Basic Rules for MATLAB Anonymous Functions

  1. Syntax: Use the @ symbol followed by input arguments and the expression.
  2. Name and Call: Assign the anonymous function to a variable for repeated use.
  3. Parent Workspace Access: Variables used in the function must exist in the parent workspace.
  4. Single Expression: Anonymous functions are limited to a single executable expression.
  5. Error Handling: Ensure that input variables are compatible with the defined expression.

Best Practices

  1. Use Descriptive Names: Assign anonymous functions to variables with meaningful names.
  2. Document Usage: Include comments when using complex anonymous functions for clarity.
  3. Limit Complexity: Avoid overly complex expressions in anonymous functions.
  4. Combine with Built-In Functions: Use anonymous functions as inputs to MATLAB’s built-in functions for streamlined operations.
  5. Avoid Overuse: For large or complex tasks, consider using regular functions instead of anonymous ones.

This chapter equips you with the knowledge to create and use MATLAB anonymous functions efficiently, enabling concise and functional programming. Subsequent sections will explore syntax, examples, and practical applications.

Syntax Table

Serial No Component Syntax Example Description
1 Define Anonymous Function f = @(x) x^2; Creates an anonymous function f that squares its input.
2 Call Anonymous Function result = f(3); Calls the function f with input 3 and stores the result in result.
3 Multiple Inputs f = @(x, y) x + y; Defines a function with two inputs x and y, returning their sum.
4 Use with Built-in Function arrayfun(@(x) x^2, A) Applies the anonymous function to each element of array A.
5 Nested Anonymous Functions f = @(x) @(y) x + y; Creates a nested anonymous function that adds x and y.

Syntax Explanation

1. Define Anonymous Function

What is Defining an Anonymous Function?

Defining an anonymous function creates a one-line function without requiring a separate file.

Syntax:

f = @(x) x^2;

Detailed Explanation:

  • The @ symbol defines the input arguments.
  • The expression after @ is the function logic.
  • The function is assigned to the variable f.

Example:

f = @(x) x^2;

disp(f(4));

Output:

16

2. Call Anonymous Function

What is Calling an Anonymous Function?

Calling an anonymous function executes the defined logic with the provided inputs.

Syntax:

result = f(input);

Detailed Explanation:

  • The function variable (f) is treated like any MATLAB function.
  • Input values are passed within parentheses.

Example:

f = @(x) x^2;

result = f(5);

disp(result);

Output:

25

3. Multiple Inputs

What are Anonymous Functions with Multiple Inputs?

Anonymous functions can accept multiple inputs for more complex operations.

Syntax:

f = @(x, y) x + y;

Detailed Explanation:

  • Multiple input arguments are separated by commas within parentheses.
  • The expression uses all inputs to compute the output.

Example:

f = @(x, y) x * y;

disp(f(3, 4));

Output:

12

4. Use with Built-in Function

What is Using Anonymous Functions with Built-in Functions?

Anonymous functions are often used as arguments to MATLAB’s built-in functions like arrayfun or integral.

Syntax:

result = arrayfun(@(x) x^2, A);

Detailed Explanation:

  • The anonymous function is applied to each element of the input array A.
  • The output is an array of results.

Example:

A = [1, 2, 3];

result = arrayfun(@(x) x^2, A);

disp(result);

Output:

    1     4     9

5. Nested Anonymous Functions

What are Nested Anonymous Functions?

Nested anonymous functions create a hierarchy of functions where one function returns another.

Syntax:

f = @(x) @(y) x + y;

Detailed Explanation:

  • The first function takes input x and returns another function.
  • The returned function takes input y and computes x + y.

Example:

f = @(x) @(y) x * y;

g = f(2); % Creates a new function g(y) = 2 * y

disp(g(3));

Output:

6

Notes

  • Anonymous functions are ideal for short, reusable logic.
  • Combine with built-in functions for concise and powerful code.

Warnings

  • Overusing anonymous functions for complex tasks can make code harder to read.
  • Ensure variables used in the function are accessible in the workspace.

Real-Life Project: Anonymous Function Usage for Mathematical Modeling

Project Name: Solving a Nonlinear Equation

Project Goal:

To use MATLAB anonymous functions for modeling and solving nonlinear equations like .

Steps in the Project:

  1. Define the Nonlinear Function:
    • Use an anonymous function to represent the equation .
  2. Find Roots:
    • Use MATLAB’s fzero function to find the roots of the equation.
  3. Plot the Function:
    • Visualize the function over a range of values to understand its behavior.

Code for This Project:

% Step 1: Define the nonlinear equation

f = @(x) x^3 – 4*x + 1;

 

% Step 2: Find roots

root1 = fzero(f, -2); % Initial guess near -2

root2 = fzero(f, 1);  % Initial guess near 1

 

disp([‘Root 1: ‘, num2str(root1)]);

disp([‘Root 2: ‘, num2str(root2)]);

 

% Step 3: Plot the function

x = linspace(-3, 3, 100);

y = f(x);

figure;

plot(x, y, ‘b-‘, root1, f(root1), ‘ro’, root2, f(root2), ‘ro’);

grid on;

title(‘Nonlinear Equation: f(x) = x^3 – 4x + 1’);

xlabel(‘x’);

ylabel(‘f(x)’);

legend(‘f(x)’, ‘Roots’);

Save and Run:

  1. Save the script as nonlinear_model.m.
  2. Run the script in MATLAB.

Expected Output:

Console Output:
Root 1: -1.879

  1. Root 2: 1.532
  2. Plot:
    • A plot showing the function curve and the roots marked with red circles.

Learning Outcomes:

  • Understand how to define and use anonymous functions for mathematical modeling.
  • Learn to solve equations using MATLAB’s built-in functions.
  • Gain insights into visualizing functions and their solutions.