07 – January 31

Writing functions in MATLAB

  • All function must have the following line as the first line of code
    • function res = funcName(input1, input2, …)
      • where res is the output and can be multiple outputs ([res1, res2, …])
        • you can also return multiple variables in a structure, these variable can be of different types, e.g.,
          • res.val1 (integer)
          • res.val2 (cell)
          • res.val3 (string)
      • where funcName is the name of the function
        • don’t name functions the same as built-in MATLAB functions, as it will render these functions inaccessible – MATLAB will generate a warning on start-up if you have a naming conflict
      • where (input1, input2, …) is the list of the inputted variable
        • regardless of what the inputted variable are named when the function is called, they are always referred to by the names defined in (input1, input2, …) within the function
    • Name your file ‘funcName.m’
    • It is useful to also include a comment header with your function, this is the information that will print out when you type ‘help funcName’
    • You can have multiple functions in a file which is useful if there is a routine in your function that is repeated but isn’t particularly general
      • To do this you would type ‘end’ after the code for the main function and then type ‘function res = suFuncName(input1, input2, …)’ on a new line
    • More details (and examples) about functions are available in the MATLAB help documentation.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *