Anda di halaman 1dari 8

MT1242: Command Structures in Matlab

Command Structures in Matlab

We will examine some of the basic programming features of matlab by introducing some of the basic commands such as if, for, while and else. Since matlab is compiled using the language C, some of you may notice similarities in the programming structures.

5.1

Using the if command

The if command is probably the most basic of all the programming commands and, as its name suggests is used in situations where when something specic happens to a variable, we tell matlab to perform some operation. For example, suppose that we had a program which checked the value of some variable, a say, and if its value was larger then 3 we wanted to consider half that value then we would use the following matlab commands in a script M-le: a=pi; if a>3 a=a/2 end Since is clearly bigger than 3, when we press F5 matlab returns the value Window a= 1.5708 5.1.1 Using else and elseif within an if routine
2

for a in the Command

A more useful way of utilizing the if command is to use else and elseif as well. In this situation, we can specify a number of possible outcomes for a variable depending on the particular value it takes. Whereas in the previous example, we only specied an outcome if the variable a was bigger than 3, this time we could specify outcomes depending on whether a is smaller than 1, between 1 and three or if it was bigger than 3: a=exp(1); if a<1 a=2*a elseif 1<a<3 a=a-1 else a=a/2 end Since a lay between 1 and 3, the elseif part of the loop was utilized a= 1.7183

5.2

Using the for command

The for loop is probably the most useful of all the matlab programming commands.The simplest situation in which a for loop arises is that where a statement is executed with some variable equal to each value specied:

MT1242: Command Structures in Matlab a=1; for i=1:21 a=a+2*i; end a which produces a= 463

We may not want the statement evaluated for every value of i , but perhaps every second value instead: a=1; for i=1:2:21 a=a+2*i; end a Pressing F5 gives a= 243 The variables i and j are commonly used to denote integer values in for loops in computer programs. Some care is necessary within Matlab as these letters are usually reserved to denote 1 during complex arithmetic. If these letters are used we must type clear before beginning any complex arithmetic. An alternative way of dening a for loop is to use vector notation: for i = [pi pi/2 pi/3 pi/4] disp([cos(i), sin(i)]) end Running the script M-le produces -1.0000 0.0000 0.5000 0.7071 0.0000 1.0000 0.8660 0.7071

The disp command, tells matlab to print the value of a variable without the name of the variable or ans being displayed. Multiple for loops are permitted and can of course be nested, by which we mean one for loops appears within another. The following code produces a 5 5 symmetric matrix: n=5; A=eye(n); for j=2:n for i=1:j-1 A(i,j) = i/j; A(j,i) = i/j; end end

MT1242: Command Structures in Matlab

5.3

Using the while command

The while loop has the form: while <expression> {statements} end and it diers slightly from the for loop in that it executes the statements for as long as the expression is true. For example, we can approximate the smallest nonzero oating point number using a while loop: x=1; while x>0 xmin=x; x=x/2; end xmin which gives 10324 and is represented in Matlab as xmin = 4.9407e-324

5.4

Relational operators

Relational operators are used to specify the conditions for the for, elseif and while statements. The syntax of these statements is given in the following table: A < B A > B A <= B A >= B A == B A = B less than greater than less than or equal to greater than or equal to equal to not equal to

Sometimes multiple conditions are required and this can be achieved by if condition1 & condition 2 if condition1 | condition 2 % for both 1 and 2 % for either 1 or 2

MT1242: Command Structures in Matlab

5.5

Writing a program in matlab

We shall now discuss the formal process of writing a matlab script. We are interested rst and foremost in writing code that will do the job required, but we will also want it to be clearly written and commented. 5.5.1 One dimensional Cellular Automata

We examine an application that arises in biology. Consider a one dimensional chain of cells:

although potentially innite, we shall assume this to be nite for the purposes of modelling the process. Each cell is in one of two states, alive or dead, which we shall assign the numbers 1 and 0 to respectively. For any given cell, its neighbourhood consists of those cells to the immediate left and right. Given a pattern of alive and dead cells, we will use the following rules to determine how the cells should grow:

Since matlab is not so good at interpreting pictures, we shall represent this gure by an array:

MT1242: Command Structures in Matlab State of Nbhd 000 001 010 011 100 101 110 111 Future state of Nbhd 000 011 000 011 110 101 110 101 Future state of cell 0 1 0 1 1 0 1 0

Notice that a cell remain alive or becomes alive if only one of its neighbours is also alive. If neither is alive, the cell dies from isolation, or if both are alive it dies from over-population. Suppose that we are interested in the state of all of the cells after 50 generations. To work this out manually is possible but would take us a very long time, depending on the number of cells. However, matlab could produce the answer very swiftly. We shall now examine how to build an m-le to do the required calculations and to plot the output. To start with we dene a vector containing the current state of the cells and one for the future state of the cells: a=zeros(1,100); newa=zeros(1,100); To ease the calculation slightly, we limit ourselves to the case of 100 cells. We must now specify the initial conditions. In order for the system to evolve, it is necessary to start with at least one cell alive. a(50)=1; g=0; max=50; For convenience we chose the middle cell to start alive. The constants g and max, dene the current generation and the maximum number of generations we wish to consider. Again for convenience we have chosen max to be 50. We now specify a matrix B which will contain information about the cells as they evolve. The rst row of B will simply be the vector a: B(1,:)=a; The : is used to tell matlab that all the elements of a form the rst row of B . This saves us having to use a for loop, specifying the position of each element of a in B and is a simple example of optimizing a program. At this point we have all the initial setup specied and are now ready to tell matlab how to determine future generations of the system: while g<max, for i=2:99, We use the while loop to tell matlab to stop the calculation once we have reached the maximum generation value max. Note that the for loop runs from 2 to 99. This is because each cell requires a neighbour to the left and right, and the cells numbered 1 and 100 only have a single cell to the right and left respectively.

MT1242: Command Structures in Matlab

We must now tell matlab how to interpret the rules about evolution that we specied previously. To do this we must use a number of if conditions. One way would be to use an if condition for each of the eight combinations specied in the table. However, we noticed that a cell becomes alive if one and only one of its two neighbours is alive. We can write this as the following condition: if (a(i-1)+a(i+1))==1, newa(i)=1; else newa(i)=0; end This is a much simpler expression than an individual if condition for each case. We now end the for loop and move onto the next generation: end g=g+1; a=newa; B(g,:)=a; end We tell matlab to take as the vector a, the newly generated vector newa and assign it to a row of the matrix B . Once all the generations have been created we can use the command spy to look at the evolution of the cells. spy allows you to visualize the sparcity of a matrix by printing a marker in the non-zero elements of the array. Just typing spy gives >>spy
0 10 20 30 40 50 60 70 80 90 100

10

20

30

40 50 nz = 1740

60

70

80

90

MT1242: Command Structures in Matlab We want to visualize the sparcity of matrix B spy(B) Running the whole program produces the plot
0 5 10 15 20 25 30 35 40 45 50 0 10 20 30 40 50 nz = 416 60 70 80 90 100

Notice that matlab produces the graph almost instantly. Were we to try and produce the same picture, it would take a great deal of time and the likelihood would be that we would make a mistake in the calculation at some point. The graph we have produced is a well-known structure called the Sierpinski triangle or Sierpinski gasket and is a simple example of a fractal.

MT1242: Command Structures in Matlab To summarize, the code we used was a=zeros(1,100); newa=zeros(1,100); g=1; max=50; a(50)=1; B(1,:)=a; while (g<max), for i=2:99, if (a(i-1) + a(i+1))==1, newa(i)=1; else newa(i)=0; end end g=g+1; a=newa; B(g,:)=a; end spy(B)

Anda mungkin juga menyukai