How to create a function in MATLAB ?
A function is a block of statements that intend to perform a specific task. Functions allow the users to reuse the code frequently. MATLAB has several predefined functions which are ready to use such as sin(), fact(), cos() etc. MATLAB also allows the users to define their own functions.
function output_params = function_name(iput_params)
- The function starts with the keyword function.
- Returning variables of the function are defined in output_params
- function_name specifies the name of the function
- input_params are input arguments to the function
Below are some examples that depict how to use functions in MATLAB:
Example 1: Function with one output
The function calculates the mean of the input vector
mean = 6.7800
Example 2: Function with multiple outputs
The function calculates both nCr and nPr of inputs n and r.
p = 6 c = 12
Example 3: Multiple functions in a file
- stat2() function calculates the standard deviation of the input vector.
- stat1() calculates the mean of the input vector.
n = 5 ans = 3.2975
Example 4: Function with no input_params
In this program, we will create the sin_plot() function that plots the sin() function