Functions and Scripts
You will find in this section information on how to create functions and scritps and the differences between them.
The main difference between those is that functions can have input and output arguments, while script files don't and also scripts have access to the variables defined in the workspace.
where the preamble
It is important for myfun to be recognized as a function to use the exact same name (case sensitive) for the file in which the function will be stored (in this case myfun.m).
Make sure the file is saved in a location that is either in one of the paths or the working directory.
Inputs:
Definition
Scripts and functions are collections of mathlayer® code stored in m-files (files with extension .m). These files will be looked in each folder defined in path and in the current working directory.The main difference between those is that functions can have input and output arguments, while script files don't and also scripts have access to the variables defined in the workspace.
Scripts
When your code is too long to run from the console, or simply because you run the same code repeatedly, it is convenient to save it as a script.Creating scripts
Using any text editor write your mathlayer® code and save it with the extension .m. For this example we will name the file myscript.m that will contain the following code:Make sure the file is saved in a location that is either in one of the paths or the working directory.if
x<10 y = trueelse
y = falseend
Calling scripts
To run the code stored in the file myscript.m just type myscript as below:>> x = 5% initializing x
>> myscript [y:true]
Functions
Creating functions
The steps to create a function are the same as with scripts. In a text editor write your mathlayer® code and save it with the extension .m. For this example we will name the file myfun.m that will contain the following code:function
y = myfun(x)if
x<10 y = trueelse
y = falseend
where the preamble
function y = myfun(x)allows to declare the funcion myfun that will take one input argument (in this case named x) and will have one output argument (in this case y).
It is important for myfun to be recognized as a function to use the exact same name (case sensitive) for the file in which the function will be stored (in this case myfun.m).
Make sure the file is saved in a location that is either in one of the paths or the working directory.
Calling functions
Calling the function myfun defined above is done as follows:>> out = myfun(10) [out:false] >> out = myfun(8) [out:true]
Inputs/Outputs
The declaration of a function differs depending on the number of input or output arguments.Inputs:
- one input: function X = myfun(x)
- more than one input: function X = myfun(x,y)
- there is no input: function X = myfun
- one output: function X = myfun(x)
- more than one output: function [X,Y] = myfun(x)
- there is no output: function [] = myfun(x)