Department of Engineering

IT Services

Programming

The following extracts give you an idea of the permissible programming constructs:

	if all(abs(t)>0),
	  lt = log(t);
	else 
	  disp('There are zero elements in t')
	end

If you type this in, Matlab will not do anything until you have typed the final end. The layout is just for readability; you could also type

	if all(abs(t)>0), lt=log(t); else 
	disp('There are zero elements in t'), end

(but you need the comma before end).

Here is another example:

	k=1;
	while t(k) == 0,
	  k=k+1;
	end
	disp('First nonzero entry in t is:'), disp(t(k))

(Note the use of == here to mean `is equal to', whereas = means `becomes'.)

You can write `for loops' just as in other programming languages, though there is less need for them in Matlab, since you can do many operations on whole matrices simultaneously. In this example we shall count down from 10 to 1 by steps of -1. Note that the vector back is initially set to be the `empty matrix', and how it grows on each pass through the loop:

	back = []
	for k = 10 : -1 : 1,
	   back = [back, k]
	end