Functions

A particularly useful feature of MATLAB is the ability to define functions.

Walkthrough

The syntax for defining the function $y=x^2$ is as follows:

function [y] = xsquared(x)
    
    y = x^2;
Info
  1. The [y] indicates the variables that will be returned from the function: there may be multiple, e.g. [y1, y2].
  2. The (x) indicates the parameters that are passed to the function: there may be multiple, e.g. (x1, x2).

Type these commands into an M-file called xsquared.m and save this file. Now type:

xsquared(5)

and then

d=7;
xsquared(d)

Note that MATLAB also allows you to apply functions to arrays. To do this with the power function we modify the above by placing a '.' before the '^' in the above:

function [y] = xsquared(x)
    
    y = x.^2;

Now type on the command line

e=[4,5,6];
xsquared(e)