0% found this document useful (0 votes)
78 views14 pages

Chapter 7

This document introduces MATLAB programming strategies and constructs. It discusses how to structure programming problems in a step-by-step process including clearly stating the problem, describing inputs/outputs, working through a hand calculation, developing a MATLAB solution, testing the solution, and optimizing the solution. It then describes programming constructs in MATLAB like for loops, if statements, while loops, and relational and logical operators that allow control of program flow.

Uploaded by

Avk Sanjeevan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views14 pages

Chapter 7

This document introduces MATLAB programming strategies and constructs. It discusses how to structure programming problems in a step-by-step process including clearly stating the problem, describing inputs/outputs, working through a hand calculation, developing a MATLAB solution, testing the solution, and optimizing the solution. It then describes programming constructs in MATLAB like for loops, if statements, while loops, and relational and logical operators that allow control of program flow.

Uploaded by

Avk Sanjeevan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CHAPTER

MATLAB programming
You should by now have a reasonable understanding of the various building stones used to write MATLAB programs: M-files, commands, graphics etc. This chapter introduces general programming strategies, programming constructs used to control program flows, and optimisation strategies. Before starting to program you might want to keep the break command in mind. Ctrl-C (i.e. press down the Ctrl-key and C, simultaneously) will halt any program as soon as an interrupt is called (normally almost instantaneously). This is useful if you get stuck in a program execution (e.g. infinite loop).

How to program
Given a problem to solve, you have to decide how to write the program that will solve the problem. While it may be tempting to go directly to the computer and start hacking some code together, it is never the most efficient way. Efficient programming requires a structured approach. Otherwise you find yourself spending hours of debugging the program. For typical engineering computation problems, the 6-step problem-solving method developed below (mainly due to D. M. Etter, Engineering Problem Solving with Matlab, Prentice-Hall, 1993) is a very suitable structured approach. The six-step process is 1. State the problem clearly. 2. Describe the input and output information. 3. Work the problem by hand (or with a calculator) for a simple set of data. 4. Develop a MATLAB solution. 5. Test the solution using a variety of data sets. 6. Optimise the solution To illustrate the technique consider the example of computing the distance between two points in the plane. 1. Problem statement The first step is to state the problem clearly. It is extremely important to give a clear and concise problem statement to avoid any misunderstandings. Furthermore, a clear and concise statement often guides the solution. For this example, the problem statement is compute the straight-line distance between two points in a plane 2. Input/output description The second step is to describe carefully the information that is given to solve the problem (input) and then to identify the values to be computed (output). A "black box" diagram is a

useful way to represent the input/output of a problem. For the example, the "black box" diagram could look something like

point 1 distance point 2

3. Hand example

The third step is to work the problem by hand or with a calculator, using a simple set of data. This is a very important step and should not be skipped even for simple problems. This is the step in which you work out the details of the problem solution. We term the step-by-step outline typical of the solution developed here the algorithm. If you can't take a simple set of numbers and compute the output by hand (or with a calculator), then you are not ready to move on to the next step. Instead you have to reread the problem and perhaps consult reference material concerned with the appropriate algorithms for the problem you wish to solve. For the specific example considered, a hand calculation would be Let the points, p1 and p2, have the coordinates p1 = (1,5), p2=(4,7) We will compute the distance, d, between the two points using the Pythagorean theorem
p2 d p1 s1 2 d2 = (s1)2 + (s2) s2

as the basis for our algorithm. So we compute d = s12 + s2 2


= ( 4 1) 2 + ( 7 5) 2 = 13 = 3. 61

4. MATLAB solution

In step 4, we translate the algorithm developed in the hand example in to MATLAB code. One advantage of MATLAB is that the statements are very similar to the equations we use
7-2

for our hand solutions. The straight-forward MATLAB solution to the above problem would be % This program computes the straight-line distance between two points % p1 = [1,5]; % initialise point 1 p2 = [4,7]; % initialise point 2 d=sqrt((p2(1)-p1(1))^2+(p2(2)-p1(2))^2) % calculate distance
5. Testing

The final step in the problem-solving process is to test the program. Here we should first test using the hand calculation. When the MATLAB program above is executed, the computer displays the following output: d= 3.6056 If the output does not match the hand calculation, we would start reviewing both calculations (the debugging process). Having reached agreement between both solutions, we should evaluate the program for a number of other data sets to be sure that the program works.
6. Optimisation

Although the above program is valid, it is not the most efficient program in MATLAB. Optimisation will be discussed later in this Chapter. In developing this program, we failed to employ the vector nature of the problem. From the linear algebra, we recall that the distance in the plane can be generalised for n-dimensional vectors as the Euclidean distance and calculated as the 2-norm of the vector joining the two points. The vector p joining the two points would be p = p2 - p1 and the 2-norm is calculated as

d = p 2 = p p = p' p The 2-norm is the standard norm calculated for vectors by the MATLAB command norm, thus the MATLAB solution of the above problem could also be written % This program computes the straight-line distance between two points % p1 = [1;5]; % initialise point 1 (notice the vector is a column vector) p2 = [4;7]; % initialise point 2 (notice the vector is a column vector) d=norm(p2-p1) % calculate distance

Program control
The MATLAB programs that we have written so far have included only sequential steps, i.e. one step was performed after another until we had completed the computation. We often need to repeat a group of statements several times and for this purpose we can use the for loops. Frequently, we also need a selection command that allows us to select one set of statements if a specified condition is true and another if the specified condition is false (if statements). Finally, we may also need a command that allows us to repeat a group of statements while a certain condition is true (while loops). Together these types of statements
7-3

are called control statements because they allow us to control the order in which statements are executed.
for loop

The for statement has the following general structure for index = matrix statement group end The statement group between the for line and the end line is repeated as many times as there are columns in the matrix (the matrix can be replaced with any expression that results in a matrix). Each time through the loop, the index has the value of the corresponding column in the vector. Most frequently, the colon operator is used to define matrix as in for time=1:10 Some of the characteristics of the for loop are

If the matrix is the empty matrix, the loop will not be calculated. Control will pass directly to the statement immediately following the end statement. If the matrix is scalar, the loop will be executed once, with the index containing the scalar. If the matrix is a row vector as in the above, 1:10, then each time through the loop, the index will contain the next element in the vector. If the matrix is a full matrix, then each time through the loop, the index will contain the next column in the matrix Upon completion of the for loop, the index contains the last value used

Relational and logical operators, expressions, and functions

The if statement and while statement both rely on logical variables. Thus before discussing these control statements, we will discuss how MATLAB works with logical variables. A logical variable is a variable that only contains the values true or false. In MATLAB, true is represented by a non-zero element (typically 1) and false is represented by a zero. Hence, a logical matrix variable is typically a matrix in which all elements are either zero or one. MATLAB has six relational operators for comparing two matrices of equal size Relational operator < <= > >= == ~= Interpretation less than less than or equal greater than greater than or equal equal not equal

7-4

Expressions involving these operators are called logical expressions and the result is a logical matrix variable. For example, if we define a = [2 4 6] b = [3 5 1] then compute c = a<b c= [1 1 0] and d = (a~=b) d= [1 1 1] The logical operators
Logical operator Symbol

and or exclusive or not

& | xor ~

are used to compare logical (0-1) matrices. and and or perform element by element comparisons between two matrices, while not calculates the logical complement of a matrix. All the possible results are listed below A false false true true B false true false true ~A true true false false xor false true true false A|B false true true true A&B false false false true

Logical operators can be used to join up logical expressions as in e = a<b & a~=b An expression can contain several operators and the hierarchy, from highest to lowest is not, and , and or. This hierarchy can be changed by using parentheses, as in f = ~(a<b & a~=b) in which the logical expression inside the parentheses is calculated first and then "negated", compared to g = ~a<b & a~=b in which a<b is first "negated" (i.e. same as a>=b) before being compared to a~=b.

7-5

MATLAB also provides a set of powerful relational and logical functions.


any(x) for each column of x, this function returns true if any elements in the column are non-zero all(x) for each column of x, this function returns true if al elements in the column are non-zero find(x) returns a vector containing the indices of non-zero elements in x. If x is a matrix, the indices are the indices from the column vector x(:). exist('A') returns a value of 1 if A exists as a variable in the workspace, 2 if A or A.M is a file, and 0 if A does not exists. Notice, that A must be in quotes. isinf(x), isnan(x), finite(x) all return matrices of zeros and ones. isinf labels all inf elements in x as true, isnan labels all NaN elements as true, finite labels all finite elements as true. isempty(x) returns true if x is an empty matrix. isstr(x) returns true if x is a string. strcmp(string1,string2) compares two strings returning one if they are identical and zero otherwise. The comparison is case-sensitive and leading and trailing blanks are included.

if statements

The full if statement construct is if logical expression 1 statement group A elseif logical expression 2 statement group B elseif logical expression 3 statement group C ---------else statement group X end Maximum one statement group will be executed in an if statement. If the logical expression 1 is true then statement group A will be executed and all other statement groups ignored. This happens whether or not the following logical statements are true. If the logical expression 1 is false then the logical expression 2 is evaluated. If true, then statement group B will be executed and all other statement groups ignored. If false, then logical expression 3 is evaluated and so forth. If all logical expressions are false only the statement group following else will be executed. The elseif and else statements are not compulsory, for example if exist('my_fun')==2 f=my_fun(x) end

7-6

while loop

The general format of the while loop is while logical expression statement group end If the logical expression is true, the statement group is executed. Then the logical expression is evaluated again. If still true, the statements are executed again, and so on until the logical expression evaluates to false. If the logical expression never becomes false, the loop becomes infinite (remember that Ctrl-C will break a loop). It should be stressed that leaving potential infinite loops in your code is poor programming practise. We will discuss how to build in error checks in programs after studying the following example that will show a typical program containing all three types of control statements.

Thermal equilibrium problem


In this problem we will consider the temperature distribution in a thin metal plate as it reaches a point of thermal equilibrium. The four sides of the will be maintained at constant temperatures (not the same temperature for all four walls). The temperature at other points on the plate is a function of the temperature of the surrounding points. If we consider the plate to be similar to a grid
Top

Left

Right

Bottom

then a matrix can be used to store the temperatures of the corresponding points on the plate. The plate on the figure is divided into 6-by-8 temperature measurements. The shaded squares represent the sides with a known constant temperature. The problem is to determine the temperatures in the internal open squares. In the algorithm we will use, the temperature in these interior points will be set to an arbitrary value, say zero. The temperature in each internal point will be calculated as the average of the four surrounding points as illustrated below
Ti-1,j Ti,j-1 Ti,j Ti+1,j Ti,j+1

Ti,j = (Ti-1,j + Ti+1,j +Ti,j-1 +Ti,j+1 )/4

7-7

Given that this calculation will make use of the interior points and given that all the interior points were chosen arbitrarily, we will not automatically accept the first set of temperatures calculated. Instead we will compare the new temperatures calculated with the old temperatures. If the difference in any interior point is greater than some specified tolerance, we will repeat the above procedure. Ultimately, the new temperatures calculated will be within tolerance of the previous temperatures calculated and we will accept the solution. We will now apply the problem solving strategy developed above to the problem.
1. Problem statement

Determine the equilibrium temperature values for a metal plate with isothermal sides.
2. Input/output description
isothermal temperatures grid size tolerance equilibrium temperatures

3. Hand example

For our test example, we will assume the matrix contains four rows and four columns, the isothermal temperatures are 100 on the top and sides and 50 on the bottom, and we use a tolerance of 40. The iterations would look something like this
Initial temperatures

100 100 100 50 100 100 100 50 100 100 100 50

100 0 0 50 100 50 37.5 50

100 0 0 50 100 50 37.5 50

100 100 100 50 100 100 100 50

First iteration

Second iteration

100 100 100 71.875 71.875 100 59.375 59.375 100 50 50 50

Since none of the temperature changes between first and second iteration exceeds the tolerance value of 40, the temperatures in the second iteration is accepted as the equilibrium temperatures.

7-8

4. MATLAB solution

% This program initializes the temperatures in the metal plate and computes the equilibrium % temperatures based on a tolerance value. % Initial values rows = 4; % Number of rows cols = 4; % Number of columns top =100; % Top temperature right=100; % Right side temperature left=100; % Left side temperature bottom=50; % Bottom side temperature tol=40; % Tolerance temperature % Initialize matrices old = zeros(rows,cols); old(1,:) = top+zeros(1,cols); % Notice this construct create a row vectors with 'cols' old(:,1) = left+zeros(rows,1); % no. of columns all having the value 'top'. Same idea old(:,cols) = right+zeros(rows,1); % for all these four lines. old(rows,:) = bottom+zeros(1,cols); % disp('Initial temperatures') disp(old) new = old; equilibrium = 0; while ~equilibrium for m=2:rows-1 for n=2:cols-1 new(m,n) = (old(m-1,n)+old(m+1,n)+old(m,n-1)+old(m,n+1))/4; end end if all(new-old<=tol) equilibrium = 1; % Tolerance met disp('Equilibrium temperatures') disp(new) end old = new; end
5. Testing

If we use the data from the test example, the output is Initial temperatures 100 100 100 100 100 0 0 100 100 0 0 100 50 50 50 50 Equilibrium temperatures 100.0000 100.0000 100.0000 100.0000 100.0000 71.8750 71.8750 100.0000 100.0000 59.3750 59.3750 100.0000 50.0000 50.0000 50.0000 50.0000 7-9

6. Optimisation

The optimisation will be performed later in this chapter.


Exercise 7.1

The tolerance is an important variable in this problem solution. Try using a tolerance of 1.
Exercise 7.2

Another important variable in this problem solution is the grid size. Try using a grid size of 10-by-10.
Exercise 7.3

Use a contour plot to visualise the results from exercise 7.2.

return, break, and error commands


It is often desirable to be able to jump out of a loop or a function under certain conditions without properly finishing the loop or function.
return causes a normal return to the invoking function or the MATLAB prompt. return is frequently used to deal with special cases. For example, in a function calculating the determinant of a matrix the special case of an empty matrix may be dealt with as

function d = det(A) %DET det(A) is the determinant of A. if isempty(A) % Special case of empty matrix d=1; return end % normal calculation follows ... Obviously a similar result could be achieved using an if-statement. If the normal computation is long, however, the clarity of the program may be lost.
break terminates the execution of for and while loops, transferring control the line following the end statement. In nested loops, break exits from the innermost loop only. error('message') displays the text in the quoted string and causes an error return to the MATLAB prompt.

As discussed earlier, good programming practise calls for avoiding the potential for forming infinite loop. This is typically achieved by introducing a maximum number of iterations allowed and an iteration counter to keep track of the present number of iterations. Using a while loop the construct would look something like Nmax = 100; iterations=0; while condition 7-10

iterations=iterations+1 if iterations>Nmax error('Maximum iterations reached') end statement group end disp(['solution found in ',int2str(iterations),' iterations]) An alternative to this approach is to use an external for-loop together with a break. This looks something like Nmax = 100; for iterations=1:Nmax statement group A if condition % solution found break end statement group B end if (iterations==Nmax) error('Maximum iterations reached') end disp(['solution found in ',int2str(iterations),' iterations']) The latter approach has the advantage that the condition statement can be placed anywhere in the loop. Hereby, one can avoid the pre-loop statements often required when using the while construct. On the other hand, the while loop statement is typically a bit more clear and whether you use the one or the other is a matter of personal taste. .

Debugging
Writing a program that works the first time is a very rare event. Typically, the coding goes through a series of iterations of running the program and fixing errors called the debugging process. This process is almost always extremely time-consuming, and it is useful to try to design any program so that debugging will be as straight-forward as possible. A simple form of debugging involves removing semicolons at the end of statements and inserting display commands, so that you can see the result of any calculation. For the size of programs, we consider in the remainder of this book this will suffice. MATLAB includes an M-file debugger for use when writing larger programs. This is however beyond the scope of this text.
Exercise 7.4

The equilibrium temperature problem contains an open ended while loop. Rewrite the program using the for loop construct above to remove the potential risk of forming an infinite loop. At the same time, display the number of iterations required to reach a solution.

7-11

Optimising programs
When a program is working, it is worthwhile to consider whether the program performs optimally. Whether or not to try optimising the program depends very much on how often you'll need the program and how long it takes to run. If you only need the program a couple of times or if the program only takes a couple of seconds, it is probably not worthwhile spending time on optimising it. For larger programs, it is important first to make a break down analysis of time consumption in the program. It makes little sense to spend time optimising a 2 second function block in a program that runs for half an hour. The timing functions discussed in Chapter 3 can be used to measure both true and cpu time. Another function is flops that will tell you the number of flops (floating point operations) performed in the session. The flops counter can be reset during a session using flops(0). Having identified the big time consuming blocks in a program, you would first see if these functions could be written more efficiently in MATLAB. A couple of hints are

Try to rewrite any for-loop to matrix form. Anything that can be calculated in parallel (i.e. is not dependent on previous calculations) should be calculated in vector form. Consider the calculation of the sample standard deviation discussed in Chapter 3

s=

(x
k =1

m)

N 1

Assuming the mean, m, is already calculated, this computation could be done using the for-loop ss = 0; for i=1:n ss=ss+(x(i)-m)^2; end s = sqrt(ss/(n-1)) In MATLAB, however, it is much more efficient to use the matrix computation >> s= sqrt((x-m)' * (x-m) /(N-1));

If you add elements to a matrix in a for-loop make certain to initialise the matrix. MATLAB will allow you to increase the size of a matrix interactively, but it wastes time. Consider calculating the cumulative product series of a vector of length n. This can be done using cumprod(1) = x(1) for i=2:n cumprod(i) = cumprod(i-1)*x(i) end MATLAB will automatically increase the length of the cumprod vector as needed. This however wastes time. It is more efficient to allocate the full cumprod vector by the command cumprod=zeros(n,1)

7-12

before doing the for loop.

Never use repeated calls to a script M-file, always use a function M-file. Function M-files are translated once into memory and will run faster in any later calls. Script M-files are translated line by line every time they are called.

If you still need to improve speed after having optimised the MATLAB code, you'll need to use MEX-files, i.e. C or Fortran programs linked to MATLAB. This process is not trivial and is beyond the scope of this Workbook.
Exercise 7.5

Perform a break down analysis of the computing effort in the thermal equilibrium program. Use both cputime and flops. Consider ways of optimising the program.

SUMMARY
In this chapter a structured programming technique has been introduced. The technique has 6 steps 1. State the problem clearly. 2. Describe the input and output information. 3. Work the problem by hand (or with a calculator) for a simple set of data. 4. Develop a MATLAB solution. 5. Test the solution using a variety of data sets. 6. Optimise the solution The chapter also introduced the three different program control constructs used in MATLAB. The for loop construct is used to repeat a statements group a given number of times. The if statement is used to choose between different possible statements groups. The while loop is used to continue performing a statement group while a certain condition remains true. A number of special characters and functions were introduced to deal with logical variables.
relational operators

< <= > >= == ~= & |


xor

less than less than or equal greater than greater than or equal equal not equal and or exclusive or not

The logical operators

relational and logical functions.

7-13

any all find exist

for each column of x, this function returns true if any elements in the column are non-zero for each column of x, this function returns true if al elements in the column are non-zero returns a vector containing the indices of non-zero elements in x. If x is a matrix, the indices are the indices from the column vector x(:). returns a value of 1 if A exists as a variable in the workspace, 2 if A or A.M is a file, and 0 if A does not exists. Notice, that A must be in quotes. all return matrices of zeros and ones. isinf labels all inf elements in x as true, isnan labels all NaN elements as true, finite labels all finite elements as true. returns true if x is an empty matrix returns true if x is a string. compares two strings returning one if they are identical and zero otherwise. The comaprison is case-sensitive and leading and trailing blanks are included.

isinf, isnan, finite

isempty isstr strcmp

Other functions return break error flops

causes a normal return to the invoking function or the MATLAB prompt. terminates the execution of for and while loops, transfering control the line following the end statement. displays a text string and causes an error return to the MATLAB prompt. Displays and zeros the MATLAB flop counter.

7-14

You might also like