Functions

If you want to store your matlab code (to hand in your homework or to be able to return to it later, for example), you will have to create an m-file in the editor. Once you type something an m-file you can run it anytime. To start the editor, type edit in the command window. Now you can type any code there and run it at once, by clickin Run at the top. It is good practice to use ;, so that you don't have a lot of random stuff showing up on your screen for a very long program.

In matlab, there are many ways to define a function. If your function is expressed through a relatively simple formula, then it makes sense to define anonymous function as follows:

Another version of anonymous function is a conditionally defined function:

syms x
f = piecewise(0< x< 1, 1-x, 1< x, 0)

Any function that is not anonymous must be defined within a m-file in matlab. A function (like a function in Math class) can essentially do the same thing to many different inputs. For example, one might want to write a function that takes some x as input and calculate three times it's squareroot. The code will look like this:

    function s=threesquareroot(x)
    s=3*sqrt(x)
    end

Once you have saved and ran this m-file once, you can call this function anytime. For example, you might want to then calculate

    B=threesquareroot(4)

For many complex tasks it is very useful to break them up into functions, which will also make your code more flexible. In any programming language, it is important to write comments which explain what complex programs are doing. In matlab, starting a line with a % sign will write a comment, which is not evaluated when you write a program. So for example
%We let x be 2
x=2;
just makes x 2, but does not display the text part when you run it.

 

Built-in Functions


Many of the functions you may be interested in using are already built-in to matlab.

For example, all of your favourite trig functions are defined:
* sin(x): calculates the sine of x
* cos(x): calculates the cosine of x
* tan(x): calculates the tangent of x
* sinh(x): calculates the hyperbolic sine of x
* acos(y): calculates the arccosine (inverse cosine) of y

which is a complex number.

The exponential function e^x is defined. The syntax is a little different that what you may be used to:
* exp(x): calculates the exponential of x

All of these functions work perfectly well with vectors and matrices. For example, if V is a vector, then cos(V) returns a vector whose elements are the cosine of the corresponding elements in V.