User-Defined Functions in MATLAB

MATLAB Tutorial

🧩 User-Defined Functions in MATLAB

User-defined functions in MATLAB allow you to create your own functions to perform specific tasks.

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

function output = functionName(input)
statements
end

📌 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

25

3️⃣ Function with Multiple Inputs


 

🔸 Call


 

Output

30

4️⃣ Function with Multiple Outputs


 

🔸 Call


 

Output

9
20

5️⃣ Function Without Output


 

🔸 Call


 

Output

Hello MATLAB

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

  • function keyword is mandatory

  • Variables 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 .m files

  • Essential for structured MATLAB programs

You may also like...