Scripts and Functions in MATLAB
Last Updated :
14 Dec, 2022
In MATLAB there are a different kinds of files dedicated to MATLAB codes. They are the following:
- Script
- Live Script
- Function only file
- 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
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
fac = fact(5)
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:
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
Share your thoughts in the comments
Please Login to comment...