MATLAB Language                
            funzioni
        
        
            
    Ricerca…
Esempio di base
Il seguente script MATLAB mostra come definire e chiamare una funzione di base:
myFun.m :
    function [out1] = myFun(arg0, arg1)
        out1 = arg0 + arg1;
    end
terminale :
    >> res = myFun(10, 20)
    res =
        30
Uscite multiple
Il seguente script MATLAB mostra come restituire più output in una singola funzione:
myFun.m :
    function [out1, out2, out3] = myFun(arg0, arg1)
        out1 = arg0 + arg1;
        out2 = arg0 * arg1;
        out3 = arg0 - arg1;
    end
terminale :
    >> [res1, res2, res3] = myFun(10, 20)
    res1 =
            30
    res2 =
            200
    res3 =
            -10
Tuttavia MATLAB restituirà solo il primo valore quando assegnato a una singola variabile
    >> res = myFun(10, 20)
    res =
            30
L'esempio seguente mostra come ottenere un output specifico
    >> [~, res] = myFun(10, 20)
    res =
            200
nargin, nargout
 Nel corpo di una funzione nargin e nargout indicano rispettivamente il numero effettivo di ingresso e di uscita fornito nella chiamata. 
Ad esempio, possiamo controllare l'esecuzione di una funzione in base al numero di input forniti.
myVector.m :
function [res] = myVector(a, b, c)
    % Roughly emulates the colon operator
    switch nargin
        case 1
            res = [0:a];
        case 2
            res = [a:b];
        case 3
            res = [a:b:c];
        otherwise
            error('Wrong number of params');
    end
end
terminale:
>> myVector(10)
ans =
    0    1    2    3    4    5    6    7    8    9   10
>> myVector(10, 20)
ans =
   10   11   12   13   14   15   16   17   18   19   20
>> myVector(10, 2, 20)
ans =
   10   12   14   16   18   20
In modo simile possiamo controllare l'esecuzione di una funzione in base al numero di parametri di output.
myIntegerDivision :
function [qt, rm] = myIntegerDivision(a, b)
    qt = floor(a / b);
    if nargout == 2
        rm = rem(a, b);
    end
end
terminale :
>> q = myIntegerDivision(10, 7)
q = 1
>> [q, r] = myIntegerDivision(10, 7)
q = 1
r = 3