Functions

User-Defined Function Examples:

Techique 1: All in one file


% File: myscript.m

    x = 5;
    y = 16;
    z = myfunc(x, y);

    function r = myfunc(a, b)
        r = a^2 - b;
    end
    

Technique 2: Functions in separate files

myscript.m
        x = 5;
        y = 16;
        z = myfunc(x,y);
      
myfunc.m
        function r = myfunc(a,b)
        r = a^2 - b;
        end
      

Matlab data container examples

Array:

        myarr = [ 11, 12, 13;
          24, 25, 26 ];

    myarr(2,3)
  

Cell array:

    mycellarr = {1, 'a', myarr};

    mycellarr{2}
  

Structure:

        mystr = struct('name', 'Ahmet', 'number', 12345)

        mystr.name

        mystr.number
  

Matlab function handles

Examples of how to define and use a function handle:

    fh = @(r)(pi*r^2)

    fh(5)


    fh2 = @(r) myAreaCalcFunc(r);

    fh2(5)


    function a = myAreaCalcFunc(r)
        a = pi*r^2;
    end
  
Practice Questions



Answers to the Practice Questions


For more details, please contact me here.