Functions let you do a specific task. User defined functions are the functions created by the users according to their needs. This article explains how the user defined function in MATLAB is created.
Syntax : function [a1,…,an] = func(x1,…,xm)
func is the function name
a1,…,an are outputs
x1,…,xm are inputs
Function name is required, whereas input and output arguments are optional.
For making a user defined function in MATLAB, go to Home -> New -> Function. The function template appears as-
function [outputArg1,outputArg2] = untitled(inputArg1,inputArg2)
% UNTITLED Summary of this function goes here
% Detailed explanation goes here
outputArg1 = inputArg1;
outputArg2 = inputArg2;
end
Change the function name and save the file with the changes made. Save the file either in the current folder or in a folder on the MATLAB search path. The name of the function and the file should be same. For example, to create a function for calculating factorial, the code is:
function f = fact(n) f = 1; i = 1; while i <= n f = f * i; i = i + 1; endend |
Save it and it can be run from the command window. The value of the fact() function returned, can also be stored in a variable. Code output for different values of n being passed :

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.
Recommended Posts:
- Matlab | Edge Detection of an image without using in-built function
- Matlab program to rotate an image 180 degrees clockwise without using function
- Calling a Python function from MATLAB
- Edge detection using in-built function in MATLAB
- Noise addition using in-built Matlab function
- Extract bit planes from an Image in Matlab
- Image Processing in MATLAB | Fundamental Operations
- MATLAB | RGB image representation
- MATLAB | RGB image to grayscale image conversion
- MATLAB | Complement colors in a Binary image
- MATLAB | Converting a Grayscale Image to Binary Image using Thresholding
- MATLAB | Complement colors in RGB Image
- MATLAB | Complement colors in a Grayscale Image
- Draw Switzerland Flag Using Matlab
- MATLAB | Display histogram of a grayscale Image
- LSB based Image steganography using MATLAB
- Draw Sweden Flag using matlab
- Difference Between MATLAB and Scilab
- How to draw Japan flag using MATLAB
- Draw Kuwait Flag using MATLAB
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

