Revision as of 12:07, 18 December 2008 by Mcwalker (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Writing functions in matlab can save you the trouble of typing the same lines of code over and over again. Functions are written in m-files. Open MATLAB, then go to file->new->m-file. Let's begin with an empty function named test that does nothing.

function test()

That was easy. Now, save the file as test.m. Every function you write must have the same name as the name of the m-file that contains it. A function foo() would be in foo.m, bar() would be in bar.m, and so on. Go to the matlab input and type test() to execute your function. Nothing happens, since we only made an empty function.

Now, let's try and make our function do something. Let's modify our file like so:

function test()

fprintf('Hello World\n')

Now save the function and execute it again. As you can see, anything that happens within your function will execute every time you call it from the main window. Whats the point of this? Let's give it an input, and get an output instead. We'll add two numbers:

function x = test(a,b)

x = a+b;

As you can see by running this code, you can give your functions inputs, and they will give you outputs. You can give your functions as many inputs as you want. In the prompt, try typing y = test(5,6). You will see that y is now equal to 11. The function will return the value of x as whatever it is equal to when the function finishes.

What if you want multiple outputs, you ask? Easy. Lets change our code to return a number of outputs. You can return an arbitrary number of outputs with your function, just like inputs.

function [x, y, z]? = test(a,b)

x = a+b;

y = a-b;

z = a*b;

Go back to the main prompt, and type [a,b,c]? = test(6,4). You will see that now a = 10, b = 2, and c = 24.

Alumni Liaison

Ph.D. on Applied Mathematics in Aug 2007. Involved on applications of image super-resolution to electron microscopy

Francisco Blanco-Silva