e-Mathematics > Matrix Algebra

Defining Functions

In its simplest form, the definition of a function named “boo” looks like this:

function zz = boo(i,j)
  zz = i + j;

The function boo is saved as “boo.m” under the current working directory. Here “i” and “j” in “zz = boo(i,j)” are the function's arguments: i and j are used to hold the values given to the function. In most cases, you will want to get some information back from the functions you define. The variable “zz” in “zz = boo(i,j)” is the one that will hold the value to be returned by the function. In order to evaluate the function boo() at the prompt

x = boo(3,4)
It returns the value 7 and stores it to the variable x.

When the function is called, the variable “nargin” is automatically initialized to the number of arguments passed to the function.

function zz = increment(x)
  if(nargin >= 1)
    zz = x + 1;
  else
    zz = 0;
  end

The above function return the value "0" when it is called without any argument.

x = increment()

The input (the arguments) of a function can be a vector or a matrix, and so is the output. In the example below the function AR3() takes the parameter vector a and the vector x of initial values, and it generates data recursively by

  x(t) = a(1) * x(t-1) + a(2) * x(t-2) + a(3) * x(t-3)
from t = 4 to t = n. Then it return the vector of size n.

function x = AR3(a,x,n)
  for t = 4:n
    x(t) = a(1) * x(t-1) + a(2) * x(t-2) + a(3) * x(t-3);
  end

Note that the input vectors "a" and "x" must be prepared before calling the function "AR3()".

a = [1.3 -0.8 -0.2]
x = [10.4 10.8 11.2]
w = AR3(a,x,20)
plot(w)

In the operation above, the return vector is stored in a variable w. If you use the variable x for the return value

x = AR3(a,x,20)
it may have unintended results.


© TTU Mathematics