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:

 

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. 

Similar Reads

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

Functions in MATLAB

...