Skip to main content

13.7) Writing Functions


  • Whilst Matlab offers a wealth of in-built functions, there may be times when you want to develop your own functions
  • We can create our own Functions that work with inputs and generate outputs
  • We do this in the Matlab Editor and create a M-function file which, like a script file, is a text file with a .m extension
  • The first line of a function is key. It defines 1) that the file is a function, 2) the output variables of the function, 3) the function name, and finally 4) the input variables
  • Lets create a simple function that takes two inputs and then adds them together
  • [matlab]
    >> open MyFirstFunction
    [/matlab]

  • Within the Matlab Editor Window we then enter the following text:
  • [matlab]
    >> function [out] = MyFirstFunction(a,b)
    >> out=a+b;
    [/matlab]

  • After saving our new function (with the name MyFirstFunction.m) we can then run it at the Matlab Command line
  • [matlab]
    >>x=4; y=7;
    >> z=MyFirstFunction(x,y)
    z=11
    [/matlab]