Open In App

Scripts and Functions in MATLAB

In MATLAB there are a different kinds of files dedicated to MATLAB codes. They are the following:

  1. Script
  2. Live Script
  3. Function only file
  4. Class file

Now only the live script is the only one of these which has a different extension name; all other three use the standard .m extension. In this article, we shall compare the script and function files. 



Scripts in MATLAB 

A script file is an ordinary MATLAB file that could contain any code except a class definition. See the following example which creates and displays a magic square.

Example 1:






% MATLAB Code
mag = magic(5);
disp(mag)

We create a script file named geeks.m and write the above code into it. Output:

 

Now, a script file can also contain a function definition in it. The syntax for the same is

—code—
— Function Definitions—

It is mandatory that the function definitions must be written after all the codes in the script.

While declaring functions in a script file, keep the following things in mind:

In the following example, we will create a function to calculate the factorial of a given number and call it in the same script. 

Example 2:




% MATLAB code 
fac = fact(5)
  
%function to calculate factorial
function y=fact(n)
    if(n<=0)
        y=1;
    else
        y=n*fact(n-1);
    end
end

Output:

 

Functions in MATLAB

As seen in the previous section, a script file can contain a locally declared function. Now, traditionally a function in MATLAB is defined more globally by creating it in its specified file. A file that contains a function only needs to fulfill following conditions:

See the following example in which we create a function ‘geeks’ in a file named geeks.m. This function will return the URL of GeeksForGeeks.

Example 3:




% MATLAB code for 
% function
function y=geeks
end

Output:

 

As it can be seen that the file name is same as the function name, and it is globally accessible.


Article Tags :