Anonymous Functions in MATLAB

⚡ Anonymous Functions in MATLAB
They are widely used for quick calculations, callbacks, and functional programming.
MATLAB is developed by MathWorks.
🔹 What Is an Anonymous Function?
An anonymous function:
Is defined using
@Contains a single expression
Is stored in a function handle
Does not require a function file
1️⃣ Basic Syntax
2️⃣ Simple Anonymous Function
🔸 Example: Square of a Number
Output
3️⃣ Anonymous Function with Multiple Inputs
Output
4️⃣ Using Anonymous Functions with Arrays
Output
📌 Use element-wise operators (.^, .*, ./).
5️⃣ Anonymous Function with Built-in Functions
🔸 Using arrayfun
Output
6️⃣ Anonymous Function for Plotting
📌 Plots sine wave without creating a function file.
7️⃣ Passing Anonymous Function as Argument
Output
8️⃣ Anonymous Functions with Multiple Outputs (Not Allowed)
❌ Anonymous functions cannot return multiple outputs.
✔ Use normal functions for multiple outputs.
⚠️ Important Notes
Limited to one expression
Supports multiple inputs
Very useful for short tasks
Stored as function handles
🎯 Interview Questions: Anonymous Functions
🔹 Q1. What is an anonymous function in MATLAB?
Answer:
A one-line function defined without a function file using @.
🔹 Q2. What symbol is used to define an anonymous function?
Answer: @
🔹 Q3. Can anonymous functions have multiple inputs?
Answer: Yes.
🔹 Q4. Can anonymous functions return multiple outputs?
Answer: No.
🔹 Q5. Where are anonymous functions commonly used?
Answer: Callbacks, plotting, optimization, quick calculations.
🔹 Q6. What is a function handle?
Answer: A variable that stores a reference to a function.
🔹 Q7. Why use anonymous functions instead of normal functions?
Answer: For simplicity and quick one-line operations.
✅ Summary
Anonymous functions are short and powerful
No
.mfile requiredDefined using
@Ideal for quick and inline operations
