Open In App

Add Functions to Scripts in MATLAB

From MATLAB version 2016b, it is possible to add functions directly into a script or live script. In this article, we shall how to add functions to script files.  The syntax is simple except one rule that the function body must be written after the codes in the script.

statement 1



statement 2

.



statement N

function 1

function body

end

function N

end 

Now, let us see the same with the help of some examples. We shall start with a simple function to concatenate three strings. We create a string names geeks.m and add our function to it.

Example 1:




% MATLAB code to concatenate two strings
str1 = 'geeks';
str2 = 'for';
res=concat(str1,str2,str1);
 
%user defined function to concatenate three strings
function str=concat(x,y,z)
str=strcat(x,y,z);
end

Output:

 

Let us create another function to a script, which calculates the binomial coefficient for a given input.

Example 2:




% MATLAB code to calculate binomial coefficient of two numbers
res=combination(9,7)
 
%user defined function to calculate combination of two numbers
function out=combination(n, k)
    out = factorial(n)/(factorial(n-k)*factorial(k));
end

Output:

 

Drawbacks of Adding Functions to a Script:

The only drawback of adding a function to a script is that function cannot be used by any other script of the workspace as it is locally defined in a particular script.

Article Tags :