0% found this document useful (0 votes)
24 views7 pages

Matlab 4 Slide

Uploaded by

Yazan Z Awad
Copyright
© © All Rights Reserved
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)
24 views7 pages

Matlab 4 Slide

Uploaded by

Yazan Z Awad
Copyright
© © All Rights Reserved
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/ 7

Lecture 6 Computer Applications 0933201 Chapter 4

UNIVERSITY OF JORDAN Algorithms and Control Structures


Faculty of Eng. and Tech. Algorithms ( ΕΎϴϣίέ΍ϮΨϟ΍): an ordered sequence of
Electrical Engineering Dept. precisely defined instructions that performs some task in
Instructor: Ziad R. Al-Khatib a finite amount of time. Ordered means that the
Introduction to MATLAB 7 instructions can be numbered, but an algorithm must
have the ability to alter the order of its instructions using
for Engineers a control structure. There are three main categories of
William J. Palm III algorithmic operations:

Chapter 4
Sequential operations: Instructions executed in order.
Programming with MATLAB Conditional operations: Control structures that first
ask a question to be answered with a true/false answer
and then select the next instruction based on the answer.
Iterative operations (loops): Control structures that
repeat the execution of a block of instructions.
Z.R.K
Z.R.K 4-2 Z.R.K

Components of Advantages of structured programming


an Algorithm 1. Structured programs are easier to write because the
• Variables and values programmer can study the overall problem first and
• Instructions then deal with the details later.
• Sequences 2. Modules (functions) written for one application can
• Procedures be used for other applications (this is called
reusable code).
• Selections
• Repetitions 3. Structured programs are easier to debug because
each module is designed to perform just one task
• Documentation and thus it can be tested separately from the other
Structured modules.
From Algorithms to Programs 4. Structured programming is effective in a teamwork
Programming environment because several people can work on
A technique for designing programs in which a a common program, each person developing one
hierarchy of modules is used, each having a single entry or more modules.
and a single exit point, and in which control is passed
5. Structured programs are easier to understand and
downward through the structure without unconditional
modify, especially if meaningful names are chosen
branches to higher levels of the structure.
for the modules and if the documentation clearly
In MATLAB these modules can be built-in or user-
4-4
identifies the module’sZ.R.K
task.
4-3 defined functions. Z.R.K

Steps for developing a computer solution Table 4.1–1


1. State the problem concisely. The
2. Specify the data to be used by the program. This is Problem
the “input.” solving
3. Specify the information to be generated by the Process
program. This is the “output.”
4. Work through the solution steps by hand or with a
calculator; use a simpler set of data if necessary.
5. Write and run the program.
6. Check the output of the program with your hand
solution.
7. Run the program with your input data and perform a
reality check on the output.
8. If you will use the program as a general tool in the
future, test it by running it for a range of reasonable
data values; perform a reality check on the results.
4-5 Z.R.K 4-5 Z.R.K

Z.R.K. 2008 Page 1 of 7


Lecture 6 Computer Applications 0933201 Chapter 4

Effective documentation can be Documenting with Charts


Two types of charts aid in developing structured
accomplished with the use of programs and in documenting them.
1. Proper selection of variable names to These are structure charts and flowcharts.
reflect the quantities they represent. A structure chart is a graphical description showing how
2. Use of comments within the program. the different parts of the program are connected together.
3. Use of structure charts. Structure chart of a game program. Figure 4.1–1
4. Use of flowcharts.
5. A verbal description of the program,
often in pseudo-code. (in which natural
language and mathematical expressions are
used to construct statements that look like
computer statements but without detailed
syntax).
4-6 Z.R.K
4-7 Z.R.K

Flowcharts are useful for Finding Bugs


developing and documenting Debugging a program is the process of finding and
programs that contain removing the “bugs,” or errors, in a program.
conditional statements, Such errors usually fall into one of the following
categories.
because they can display the
1. Syntax errors such as omitting a parenthesis or
various paths (called
comma, or spelling a command name incorrectly.
“branches”) that a program can MATLAB usually detects the more obvious errors
take, depending on how the and displays a message describing the error and its
conditional statements are location.
executed. 2. Errors due to an incorrect mathematical procedure.
These are called runtime errors. They do not
Flowchart representation necessarily occur every time the program is
of the if statement. executed; their occurrence often depends on the
particular input data. A common example is
Figure 4.1–2 division by zero.
Z.R.K Z.R.K
4-8 4-9

Logical operators Table 4.3–1


To locate a runtime errors, try the following: Operator Name Definition
1. Always test your program with a simple ~ NOT ~A returns an array the same dimension as A; the
version of the problem, whose answers can new array has ones where A is zero and zeros
where A is nonzero.
be checked by hand calculations.
& AND A & B returns an array the same dimension as A
2. Display any intermediate calculations by and B; the new array has ones where both A and B
removing semicolons at the end of have nonzero elements and zeros where either A
or B is zero.
statements.
| OR A | B returns an array the same dimension as A
3. To test user-defined functions, try and B; the new array has ones where at least one
element in A or B is nonzero and zeros where A
commenting out the function line and and B are both zero.
running the file as a script. && Short-Circuit Operator for scalar logical expressions. A && B
4. Use the debugging features of the AND returns true if both A and B evaluate to true, and
false if they do not.
Editor/Debugger, which is discussed in
|| Short-Circuit Operator for scalar logical expressions. A || B
Section 4.7. OR returns true if either A or B or both evaluate to true,
4-10 Z.R.K
4-11 and false if they
Z.R.Kdo not.

Z.R.K. 2008 Page 2 of 7


Lecture 6 Computer Applications 0933201 Chapter 4

Logical functions Table 4.3–4


Order of precedence for operator types Table 4.3–2 Logical function Definition
all(x) Returns a scalar, which is 1 if all the elements in
Precedence Operator type the vector x are nonzero and 0 otherwise.
all(A) Returns a row vector having the same number of
First Parentheses; evaluated starting with columns as the matrix A and containing ones and
the innermost pair. zeros, depending on whether or not the corresp-
onding column of A has all nonzero elements.
Second Arithmetic operators and logical any(x) Returns a scalar, which is 1 if any of the elements
NOT (~); evaluated from left to right. in the vector x is nonzero and 0 otherwise.
any(A) Returns a row vector having the same number of
Third Relational operators; evaluated from columns as A and containing ones and zeros,
left to right. depending on whether or not the corresponding
column of the matrix A contains any nonzero
Fourth Logical AND ( & ). elements.
Fifth Logical OR ( | ). finite(A) Returns an array of the same dimension as A with
ones where the elements of A are finite and zeros
elsewhere.
4-12 Z.R.K
4-13 Z.R.K (continued …)

Logical functions Table 4.3–4 (continued)


Logical Operators & and the find Function
Logical function Definition
ischar(A) Returns a 1 if A is a character array and 0 therwise. >>x = [5, -3, 0, 0, 8]; y = [2, 4, 0, 5, 7];
isempty(A) Returns a 1 if A is an empty matrix and 0 otherwise. >>z = find(x&y)
isinf(A) Returns an array of the same dimension as A, with
z =
ones where A has ‘inf’ and zeros elsewhere. 1 2 5
isnan(A) Returns an array of the same dimension as A with Note that the find function returns the indices, and not
ones where A has ‘NaN’ and zeros elsewhere. (‘NaN’ the values.
stands for “not a number,” which means an In the following session, note the difference between
undefined result.) the result obtained by y(x&y) and the result obtained
isnumeric(A) Returns a 1 if A is a numeric array and 0 otherwise.
isreal(A) Returns a 1 if A has no elements with imaginary by find(x&y) in the previous example.
parts and 0 otherwise. >>values = y(x&y)
logical(A) Converts the elements of the array A into logical
values =
values.
xor(A,B) Returns an array the same dimension as A and B; 2 4 7
the new array has ones where either A or B is >>how_many = length(values)
nonzero, but not both, and zeros where A and how_many =
B are either both nonzero or both zero.
Z.R.K
3 Z.R.K
4-14 4-15

The if and else Statement When the test, if logical expression, is


performed, where the logical expression may
The if statement’s basic form is be an array, the test returns a value of true only if all
if logical expression the elements of the logical expression are true!
statements
For example, if we fail to recognize how the test works,
end
the following statements do not perform the way we
Every if statement must have an
might expect.
accompanying end statement. The
end statement marks the end of the x = [4,-9,25];
statements that are to be executed if x < 0
if the logical expression is true. disp(’Some elements of x are negative.’)
The basic structure for the use of else
the else statement is y = sqrt(x)
if logical expression
end
statement group 1
Because the test if x < 0 is false, when this program
else Flowchart of the else is run it gives the result
statement group 2
structure. Figure 4.4–2 y = 2 0 + 3.000i 5
end
4-16 Z.R.K More? See pages 201-202. 4-17 Z.R.K

Z.R.K. 2008 Page 3 of 7


Lecture 6 Computer Applications 0933201 Chapter 4
The following statements
if logical expression 1
Instead, consider what happens if we test for x positive. if logical expression 2
x = [4,-9,25]; statements
end
if x >= 0 end
y = sqrt(x) can be replaced with the more concise program
if logical expression 1 & logical expression 2
else statements
disp(’Some elements of x are negative.’) end
The elseif Statement
end The general form of the if statement is
if logical expression 1
When executed, it produces the following message: statement group 1
elseif logical expression 2
Some elements of x are negative. statement group 2
else
The test if x < 0 is false, and the test if x >= 0
statement group 3
also returns a false value because x >= 0 returns the end
vector [1,0,1]. The else and elseif statements may be omitted if not required. However,
if both are used, the else statement must come after the elseif statement
Z.R.K
to take care of all conditions that might
Z.R.K
be unaccounted for.
4-18 4-19

For example, suppose that Strings ‘ ‘


y = ln(x) for x > 10, A string is a variable that contains characters.
y = sqrt(x) for 0 <= x <= 10, Strings are useful for creating input prompts and
and messages and for storing and operating on data such
y = exp(x)-1 for x < 0. as names and addresses. To create a string variable,
The following statements enclose the characters in single quotes (’ ’). For
will compute y if x example, the string variable name is created as follows:
already has a scalar value. >>name = ’Omar Student’
if x > 10 name =
y = log(x) Omar Student
elseif x >= 0 The following string, number, is not the same as the
y = sqrt(x) variable number created by typing number = 123.
else >>number = ’123’
y = exp(x) - 1 Flowchart illustrating nested number =
if statements. Figure 4.4–4
end 123
4-20 Z.R.K More? See pages 205-208. 4-21 Z.R.K

Strings and the input Statement Strings and Conditional Statements


The prompt program on the next slide uses the
The following prompt program is a script file that allows
isempty(x) function, which returns a 1 if the array x the user to answer Yes by typing either Y or y or by
is empty and 0 otherwise. pressing the Enter key. Any other response is treated as
It also uses the input function, whose syntax is the answer No.

x = input(’prompt’, ’string’) response = input(’Want to ...


or continue? Y/N [Y]: ’,’s’);
x = input(’prompt’, ’s’) if(isempty(response))|(response==’Y’)...
|(response==’y’)
This function displays the string prompt on the response = ’Y’
screen, waits for input from the keyboard, and returns else
the entered value in the string variable x. response = ’N’
The function returns an empty matrix if you press the end
Enter key (  ) without typing anything.
4-22 Z.R.K
4-23 Z.R.K More? See pages 209-210.

Z.R.K. 2008 Page 4 of 7


Lecture 6 Computer Applications 0933201 Chapter 4

for Loops Note the following rules when using for loops
A simple example of a for loop is with the loop variable expression k = m:s:n
for k = 5:10:35
x = k^2 „ The step value s may be negative.
end Example: k = 10:-2:4 produces k = 10, 8, 6, 4.
The loop variable k is initially „ If s is omitted, the step value defaults to 1.
assigned the value 5, and x is „ If s is positive, the loop will not be executed if m
calculated from x = k^2. Each is greater than n.
successive pass through the loop
increments k by 10 and
„ If s is negative, the loop will not be executed if m
calculates x until k exceeds 35.
is less than n.
Thus k takes on the values 5, 15, „ If m equals n, the loop will be executed only
25, and 35, and x takes on the once.
values 25, 225, 625, and 1225. The „ If the step value s is not an integer, round-off
program then continues to errors can cause the loop to execute a different
execute any statements following Flowchart of a for
Loop. Figure 4.5–1
number of passes than intended.
the end statement.
4-24 Z.R.K 4-25 Z.R.K

Use of a Mask
The continue Statement One can often avoid the use of loops and branching and thus
create simpler and faster programs by using a logical array as a
The following code uses a continue statement to mask that selects elements of another array. Any elements not
avoid computing the logarithm of a negative number. selected will remain unchanged. The following session creates
the logical matrix C from the numeric matrix A .
x = [10,1000,-10,100]; >>A = [0, -1, 4; 9, -14, 25; -34, 49, 64];
y = NaN*x; >>C = (A >= 0);
1 0 1
for k = 1:length(x) The result is 1 0 1
C=
if x(k) < 0 0 1 1
continue One can use this mask technique to compute the square root of
only those elements of A given in the previous program that are
end not less than 0 and add 50 to those elements that are negative.
y(k) = log10(x(k)); The program is:
end A = [0, -1, 4; 9, -14, 25; -34, 49, 64];
C = (A >= 0);
y
A(C) = sqrt(A(C))
The result is y = 1, 3, NaN, 2. A(~C) = A(~C) + 50
4-26 Z.R.K More? See pages 210-217. 4-27 Z.R.K

while Loops The typical structure of a


The while loop is used when the looping process while loop follows.
terminates because a specified condition is satisfied, while logical expression
and thus the number of passes is not known in
statements
advance. A simple example of a while loop is
end
x = 5; For the while loop to function
while x < 25 properly, the following two
disp(x) conditions must occur:
x = 2*x - 1; 1. The loop variable must have a
value before the while
end statement is executed.
The results displayed by the disp statement are 5, 2. The loop variable must be
changed somehow by the Flowchart of the while
9, and 17.
statements. loop. Figure 4.5–3
4-28 Z.R.K
4-29 Z.R.K More? See pages 221-223.

Z.R.K. 2008 Page 5 of 7


Lecture 6 Computer Applications 0933201 Chapter 4

A simple example of a while loop is Another Example of a while Loop


x = 5;k = 0; Write a script file to determine how many terms are
required for the sum of the series 5k2 – 2k, k = 1, 2, 3, …
while x < 25 to exceed 10,000. What is the sum for this many terms?
k = k + 1; total = 0;k = 0;
y(k) = 3*x; while total < 1e+4
x = 2*x-1; k = k + 1;
total = 5*k^2 - 2*k + total;
end
end
The loop variable x is initially assigned the value 5,
disp(’The number of terms is:’)
and it keeps this value until the statement x = 2*x - 1
is encountered the first time. Its value then changes to
disp(k)
9. Before each pass through the loop, x is checked to disp(’The sum is:’)
see if its value is less than 25. If so, the pass is made. disp(total)
If not, the loop is skipped. The sum is 10,203 after 18 terms.
Z.R.K Z.R.K
4-30 4-31

The switch Structure The following switch block displays the point
The switch structure provides an alternative to using the on the compass that corresponds to that angle.
if, elseif, and else commands. Anything programmed switch angle
using switch can also be programmed using if structures.
case 45
However, for some applications the switch structure is
more readable than code using the if structure. disp(’Northeast’)
switch input expression % which can be a scalar or string case 135
case value1 disp(’Northwest’)
statement group 1 case 225
case value2 disp(’Southwest’)
statement group 2 case 315
.
.
.
disp(’Southeast’)
otherwise otherwise
statement group n disp(’Direction Unknown’)
end end
4-32 Z.R.K
4-33 Z.R.K More? See pages 225-227.

The Editor/Debugger containing two Fourier Series


programs to be analyzed. Figure 4.7–1
x(t) = a0 + 6n=1 ( an cos nZ0t + bn sin nZ0t )
Evaluate the following function:
x(t) = 0.5 + 2/S ( cost – 1/3 cos 3t + 1/5 cos5t
– 1/7 cos7t + … ) for -10 < t < 10.
By using different colors plot the following:
1- The first two terms.
2- On the same figure plot the first three terms.
3- On the same figure plot the first four terms.
4- On the same figure plot the first five terms.
5- By using the general form of the function, and by using the
for or while or … loop. Set n as input variable, On the
same figure plot the first one-
one-hundred terms.

4-34 Z.R.K More? See pages 228-234. 4-35 Z.R.K

Z.R.K. 2008 Page 6 of 7


Lecture 6 Computer Applications 0933201 Chapter 4

End of Chapter 4

Problems Page 241 - 257 !


Solve: 2, 5, 11, 16, 23, 24, 25, 33.
www.ju.edu.jo\zkhatib
Z.R.J.K
Z.R.K

Z.R.K. 2008 Page 7 of 7

You might also like