Open In App

Scripts and Functions in MATLAB

Last Updated : 14 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




% 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:

  • Function definitions must be written after all code in script file.
  • File name does not necessarily need to be same as function name.
  • All the declared functions will be local functions to that script.

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




% 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:

  • Only one parent function is allowed per file. 
  • The file name must be the same as the function name.

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




% 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads