# Matlab Functions

The real power of Matlab is as a programming language. You can write small programs, called functions, that you can then run from within Matlab, to perform repetitive tasks using different parameters.

Let's illustrate this by writing a function to evaluate Euclidean norm of any vector; that is: the square root of the sum of squares of the entries of the vector.

First, open Matlab.

Select File->New->M-file to get an edit window, where we can write the function.

Every Matlab function starts with a function statement of the form

function returnvalue = name_of_function(arg1,arg2,...)

In this case, the input argument will be the vector whose norm we want to compute, and the return value will be the norm.

We create a new vector whose entries are the squares of the entries in our input vector called vec.

Note that it doesn't matter whether vec was a row or column vector here - we just square each entry. Next, we use the built-in sum function to add up the entries in squares, and then take the square root, assigning that to the variable vecnorm. Remember that vecnorm will be returned to the Matlab session.

We put semicolons at the end of each line so that nothing prints out from the function. It runs silently. Now we save the function, using the same name as we assigned it in the function statement.

Next, we test the function on a very small vector where we can figure out the answer by hand. Let's try a 3-dimensional vector whose entries are all 1. This should have a norm that is sqrt(1^2+1^2+1^2); i.e. the square root of 3; around 1.7.

This function had only two lines. If there had been more, we would certainly have made a mistake, and would have found the simplest error using this example.

However, we are not done. Let's try a column vector.

This time we made a 16-dimensional column vector composed of ones, so that the norm should have been the square root of 16: 4. It worked again. For this simple program, we might now trust the results. If it were more complicated we would continue testing, trying to think of cases that might break the code.

Let's try one last example. We change one element of our last problem so that it is negative. That should not change the norm.

It still works. We are believers, at least for now. At some time in the future if the function seems to let us down, we will go back and test it more.

Copyright 2006 Kevin Cooper Back to Content Page