User-Defined Functions in MATLAB

🧩 User-Defined Functions in MATLAB
They help make programs modular, reusable, and easy to maintain.
MATLAB is developed by MathWorks.
🔹 What Is a User-Defined Function?
A user-defined function is a function written by the user (not built-in) that:
Accepts input arguments
Performs operations
Returns output values
Functions are saved in .m files.
1️⃣ Basic Syntax of a Function
📌 The file name must be the same as the function name.
2️⃣ Example 1: Simple Function (Square of a Number)
🔸 Step 1: Create a file squareNum.m
🔸 Step 2: Call the Function
Output
3️⃣ Function with Multiple Inputs
🔸 Call
Output
4️⃣ Function with Multiple Outputs
🔸 Call
Output
5️⃣ Function Without Output
🔸 Call
Output
6️⃣ Function Without Input
7️⃣ Local Functions
A file can contain multiple functions, but:
First function = main function
Others = local functions
⚠️ Important Rules
File name = function name
functionkeyword is mandatoryVariables inside functions are local
Functions improve code reuse
🎯 Interview Questions: User-Defined Functions
🔹 Q1. What is a user-defined function in MATLAB?
Answer:
A function created by the user to perform specific operations.
🔹 Q2. What should be the file extension of a function file?
Answer:.m
🔹 Q3. Can a function have multiple outputs?
Answer:
Yes, using square brackets [ ].
🔹 Q4. What is the scope of variables inside a function?
Answer:
Local to the function.
🔹 Q5. Can a function exist without input arguments?
Answer:
Yes.
🔹 Q6. Can a function exist without output arguments?
Answer:
Yes.
🔹 Q7. What is the first function in a file called?
Answer:
Main function.
✅ Summary
User-defined functions improve modularity
Support inputs and outputs
Saved in
.mfilesEssential for structured MATLAB programs
