Program Design and Development
In Chapter 1 we introduced relational operators, such as > and =>. and the two types of loops used in MATLAB, the for loop and the while loop. These features, plus MATLAB functions and the logical operators to be introduced in Section 4.3, form the basis for constructing MATLAB programs to solve complex problems. Design of computer programs to solve complex problems needs to be done in a systematic manner from the start to avoid time-consuming and frustrating difficulties later in the process. In this section we show how to structure
and manage the design process
Algorithms and Control Structures
An algorithm is an ordered sequence of precisely defined instructions that per- ‘forms some task in a finite amount of time. An ordered sequence means that the instructions can be numbered, but an algorithm must have the ability to alter the order of its instructions using what is called a control structure. There are three categories of algorithmic operations:
Sequential operations. These are instructions that are executed in order. Conditional operations. These e control structures that first ask a question to be answered with true/false answer and then select the next instruction based on the answer, Iterative operations (loops). These are control structures that repeat the execution of a block of instructions.
Not every problem can be solved with an algorithm and some potential algorithmic solutions can fail because they take too long to find a solution.
Structured programming is a technique for designing programs in which a hierarchy of modules is used, each having a single entry and a single exit point, and in which control is passed downward through the structure without unconditional branches to higher levels of the structure. In MATLAB these modules can be built-in or user-defined functions. Control of the program flow uses the same three types of control structures
used in algorithms: sequential, conditional, and iterative. In general, any computer prog~~an be written with these three structures. This realization
led to the development of structured programming. Languages suitable for structured programming, such as MATLAB, thus do not have an equivalent to the go to statement that you might have seen in the BASIC and FORTRAN languages. An unfortunate result of the go to statements confusing code, called spaghetti code, composed of a complex tangle of branches.Structured programming, if used properly, results in programs that are easy to write, understand, and modify, The advantages of structured programming are follows
- Structured programs are easier to write because the programmer can study the overall problem first and then deal with the details later.
- Modules (functions) written for one application can be used for other applications (this is called reusable code).
- Structured programs are easier to debug because each module is designed to perform just one task and thus it can be tested separately from other modules.
- Structured programming is effective in a teamwork environment because several people can work on a common program, each person developing one or more modules. .
- Structured programs are easier to understand and modify, especially if meaningful names are chosen for the modules and if the documentation clearly identifies the module’s task.
Top-down Design and Program Documentation
A method for creating structured programs is top-down design, which aims to describe a program’s intended purpose at a very high level initially, and then partition the problem repeatedly into more detailed .levels, one level at a’ time until enough is understood about the program structure to enable it to be coded. Table 4.1-1, which is repeated from Chapter 1, summarizes the process of top own design. In step 4 you create the algorithms used to obtain the soluation that step 5, Write and Run the Program, is only part of the top-down disign process. In this step you create the necessary modules and test them separately.
Table 4.1-1 Steps for developing a computer solution
- . State the problem concisely.
- Specify the data to be used by the program. This is the “input.”
- Specify the information to be generated by the program. This is the “output.”
- Work through the solution steps by hand or with a calculator; use a simpler set of data if necessary. 1 t
- Write and run the program.
- Check the output of the program with your hand solution.
- Run the program with your input data and r form a reality check on the output.
- If YO\! will use the program as a general tool in the future, test it by running it for
a range of reasonable data valves; perform a reality check on the results.
Two types of charts aid in developing structured programs and in documenting them. These are structure charts and flowcharts. A structure chart is a graphical description showing how the different parts of the program are connected together. This type of diagram is particularly useful in the initial stages of top-down
design. . A structure chart displays the organization of a program without showing the details of the calculations and decision processes. For example, we can create program modules using function files that do specific, readily identifiable tasks. Larger programs are usually composed of a main program that calls on the modules to do their specialized tasks as needed. A structure chart shows the connection between the main program and the modules. For example, suppose you want to write a program that plays a game, say Tic-Tac-Toe. You would need a module to allow the human player to input a move, a module to update and display the game grid, and a module that contains the computer’s strategy for selecting its moves. Figure 4.1-1 shows the structure chart of such a program. . Flowcharts are useful for developing and documenting programs that contain conditional statements, because they can display the various paths (called “branches”) that a program can take, depending on how the conditional statements are executed. The flowchart representation of the i f statement is shown
in Figure 4.1-2. Flowcharts use the diamond symbol to indicate decision points. The usefulness of structure charts and flowcharts is limited by their size. For large, more complicated programs, it might be impractical to draw such charts. Nevertheless, for smaller projects, sketching a flowchart and/or a structure chart might help you organize your thoughts before beginning to write the specific MATLAB code. Because of the space required for such charts we do not use them in this text. You are encouraged, however, to use them when solving problems.
Documenting programs properly is very important, even if you never give your programs to other people. If you need to modify one of your programs, you .
will find that it is often very difficult to recall how it operates if you have not used it for some time. Effective documentation can be accomplished with the use of
- Proper selection of variable names to reflect the quantities they represent.
- Use of comments within the program.
- Use of structure charts.
- Use of flowcharts.
- A verbal description of the program, often in pseudocode.
The advantage of using suitable variable names and comments is that they reside’
with the program; anyone who gets a copy of the program will see such documentation. However, they often do not provide enough of an overview of the . program. The latter three elements can provide such an overview
Use of natural language, such as English, to describe algorithms often results in a description that is too verbose and is subject to misinterpretation. To avoid dealing immediately with the possibly complicated syntax of the programming language, we can instead use pseudo code, in which natural language and mathematical
expressions are used to construct statements that look like computer statements but without detailed syntax. Pseudo code may also use some simple MATLAB syntax to explain the operation of the program. As its name implies, pseudo code is an imitation of the actual computer code. The pseudo code can provide the basis for comments within the program. In addition to providing documentation, pseudo code is useful for outlining a program before writing the detailed code, which takes longer to write because it must conform to the strict rules of MA1LAB. Each pseudo code instruction may be numbered, but should be unambiguous and computable. Note that MA1LAB does not ‘use line numbers except in the Debugger. Each of the following examples illustrates how pseudo code can document each of the control structures used in algorithms: sequential, conditional, and iterative operations.
Example 1. Sequential Operations
Compute the perimeter p and the area A
of a triangle whose sides are a, b, and c: The formulas are:
Example 2. Conditional Operations Given the (x, y) coordinates of a point.
compute its polar coordinates (r, (J). where
- Enter the coordinates x and y.
- Compute the hypoteneuse r.
r = sqrt(xA2+yA2)
- Compute the angle (J.
3.1 If x :::0 . theta = atan(y/x)
theta = atan(y/x) + pi
- Convert the angle to degrees.
‘theta = theta*(180/pi)
- . Display the results r and theta.
Note the use of the numbering scheme 3.1 and 3.2 to indicate subordinate clauses. Note also’ that MATLAB syntax may be used for clarity where needed. The
x= input(‘Enter the value of x: ‘):
y= input(‘Enter the value of y: ‘);
r= sqrt (xA2+yA2);
if x >= 0
theta atan (y/x);
theta atan (y/x) + pi;
disp (‘The hypoteneuse is:’)
theta = theta*(180/pi);
disp(‘The angle is degrees is:’)
Example 3. Iterative Operations
Determine how many terms are required for the sum of the series 1Ok2 – 4k + 2, k = I. 2. 3•… to exceed 20,000. What is the sum for this many terms? Because we do not know how many times we must evaluate the expression
– 4k + 2, we use a while loop.
- Initialize the total to zero.
- Initialize the counter to zero.
While the total is less than 20,000 compute the total
3.1 Increment the counter by 1.
k = k + 1
3.2 Update the total.
total = 10*kA2 – 4*k + 2 + total
4. Display the current value of the counter.
5. Display the value of the total.
The program is
total = 0;
k = q;
while total < 2e+4
k = k+l; .
total = 10*kA2 – 4*k + 2 + total;
disp (‘The number of terms is:’)
disp ( ‘The sum is:’)
Debugging a program is the process of findinJnd removing the “bugs,” or errors, in a program. Such errors usually fall into one of the following categories.
- Syntax errors such as omitting a parenthesis or comma, or spelling a command name incorrectly. MATLAB usually detects the more obvious errors and displays a message describing the error and its location.
- Errors due to an incorrect mathematical procedure. These are called run time errors. They do not necessarily occur every time the program is executed; their occurrence often depends on the particular input data. A common example is division by zero.
The MATLAB error messages usually enable you to find syntax errors. However, runtime errors are more difficult to locate. To locate such an error, try the
- Always test your program with a simple version of the problem, whose answers can be checked by hand calculations .
- Display any intermediate calculations by removing semicolons at the end of statements
- To test user-defined functions, try commenting out the function line and running the file as a script.
- Use the debugging features of the EditorlDebugger, which is discussed in
Development of Large Programs
Large programs and software, including commercial software such as MATLAB, undergo a-rigorous process of development and testing before finally being released and approved for general use. The stages in this process are typically the
- Writing and testing of individual modules (the unit-testing phase).
- Writing ofthe top-level program that uses the modules (the build phase). Not all modules are included in the initial testing. As the build proceeds,
more modules are included.
- Testing of the first complete program (the alpha release phase). This is usually done only in-house by technical people closely involved with the
program development. There might be several alpha releases as bugs are discovered and removed.
- Testing of the final alpha release by in-house personnel and by familiar and trusted outside users, who often must sign onfidentiality agreement. This is the ~ta release phase, and there might be several beta releases.
This process can take quite a while, depending on the complexity of the program and the company’s dedication to producing quality software. In the case of MATLAB 7, there were approximately nine months between the first beta release and the final release of the completed software.