MATLAB Chapter 4: 4.1 Program Design and Development

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Spring 2015

MATLAB Chapter 4
Programming with Matlab

4.1 Program Design and Development


 Table 4.1-1 Steps for developing a computer solution

1. State the problem concisely


2. Specify the data to be used by the program. This is the “input”.
3. Specify the information to be generated by the 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.
2

1
Spring 2015

4.2 Relational operators and Logical


Variables

 Table 4.2-1 Relational Operators


< less than
 <= less than or equal
> greater than
 >= greater than or equal
 == Equal to
 ~= Not equal to

 The result is either 1 (for true) or 0 (for false).


 This result can be used as a logical variable.
3

4.2 The logical function

 Recall from chapter 1 when we do >> x=[6,3,9];


logical comparisons. >> y=[14,2,9];
>> z=(x<y)

 The resulting array z is called a z =


logical array, and contains a 1
where the comparison is true and 1 0 0
zero were it is false.
>> z=(x==y)

 Not all arrays containing zeros and z =


ones are logical arrays! 0 0 1

2
Spring 2015

4.2 The logical function

 The logical array can be used for further analysis.


>> x=[6,3,9]; >> x=[6,3,9];
>> y=[14,2,9]; >> y=[14,2,9];
>> z=(x<y) >> u=[1,0,0]

z = u =

1 0 0 1 0 0

>> x(z) >> x(u)


??? Subscript indices must either
ans = be real positive integers or
logicals.
6

4.2 The logical function


 To create a logical array, the logical function can be
used. For example
>> x=[6,3,9];
>> y=[14,2,9];
>>
u=logical([1,0,0])

u =

1 0 0

>> x(u)

ans =

6
6
6

3
Spring 2015

Test Your Understanding

4.3 Logical Operators and Functions


 Table 4.3-1 Logical operators
Operator Name Definition
 ~ NOT B=~A has ones where A is zero and
zeros where A is nonzero.
 & AND A&B has ones where both A and B
have nonzero elements and zeros
where either A or B is zero.
 | OR A|B has ones where at least one
element in A or B is nonzero and zeros
where A and B are both zeros.
 && Short-circuit AND Operator for scalar logical
expressions. A&&B returns true if both
A and B evaluates to true, and false if
they do not.
 || Short-circuit OR Operator for scalar logical
expressions. A||B returns true if either
A or B or both evaluate to true, and
8
false if they do not.

4
Spring 2015

4.3 Logical Operators and Functions

 See Table 4.3-2 for order of precedence for operator


types.

4.3 Logical Operators and Functions


>> x=[0,3,9]; 9
>> x=[0,3,9]; >> x=[0,3,9];
>> y=[4,-2,9]; >> y=[4,-2,9]; >> y=[4,-2,9];
>> ~x
>> find(x&y) >> y(x&y)
ans =
ans = ans =
1 0 0
2 3 -2 9
>> x&y
>> >> (x&y)&(x|y) >> x(x&y)
ans =

0 1 1 ans = ans =

>> x|y 0 1 1 3 9

ans = >> (x>y)&(x|y) >>


>> z=(3<5)|(4==7)
1 1 1
ans =
>> x>y >> z =
0 1 0
ans = 1

0 1 0

5
Spring 2015

4.3 Logical Operators and


Functions >> xor(0,0)

ans =

0
 The exclusive OR function
>> xor(1,0)
xor(A,B) returns zeros
where A and B are either ans =

both nonzero or both zero, 1


and ones where either A or
>> xor(0,1)
B is nonzero, but not both.
ans =
 The function is defined as
1

xor(A,B) = (A|B) & ~(A&B) >> xor(1,1)

ans =

0
11
>>

4.3 Logical Operators and Functions

 Table 4.3-3 Truth Table

x y ~x x|y x&y xor(x,y)

True True False True True False

True False False True False True

False True True True False True

False False True False False False


12

6
Spring 2015

4.3 Logical Operators and Functions

>> %The following Matlab session generates the truth table in


>> %terms of ones and zeros

>> x=[1,1,0,0]';
>> y=[1,0,1,0]';
>> Truth_Table=[x,y,~x,x|y,x&y,xor(x,y)]

Truth_Table =

1 1 0 1 1 0
1 0 0 1 0 1
0 1 1 1 0 1
0 0 1 0 0 0
>>

13

4.3 Logical Operators and Functions

 Table 4.3-1 Logical functions A =


Example
1 0 3 4
5 6 7 8
 all(x) 9 10 11 12
 Returns the scalar 1 if
>> any(A)
all elements in x are
nonzero, and 0 ans =
otherwise
 any(x) 1 1 1 1
 Returns the scalar 1 if
>> all(A)
any of the elements of x
is nonzero. ans =
 If x is an mxn matrix,
1 0 1 1
columns are evaluated.
14

7
Spring 2015

4.3 Logical Operators and >>


A =
A=[1,2;0,5]

Functions 1 2
0 5

>> [u,v,w]=find(A)

u =

1
1
2

v =

1
 [u,v,w]=find(A) 2
2
 u=nonzero row indices
 v=nonzero column indices
w =
 w=nonzero values
1
2
15
5

4.3 Logical Operators and Functions

 Table 4.3-1 Logical functions


Examples
 isempty(A) Returns 1 if A is an empty matrix

 logical(A) Converts the elements of the array A


into logical values.

 etc…

16

8
Spring 2015

Example 4.3-1

 The height and speed of a projectile in function of time t:


h(t)  v 0t sinA  0.5gt 2
v(t)  v 2  2v gt sinA  g2 t 2
0 0

 v0= launching speed


 A = angle to the horizontal
 g= acceleration due to gravity

 The projectile will strike the ground when h(t)=0, which gives the time
to hit t hit  2(v 0 / g)sinA .
 Suppose A = 40°, v0= 20 m/s, and g = 9.8 m/s2. Find the times when
the height is no less than 6 m (i.e. h(t)6 m) and the speed is
simultaneously no greater than 16 m/s (i.e. v(t)16 m/s).
17

Example 4.3-1

18

9
Spring 2015

Test Your Understanding

4.4 Conditional Statements

 The if-elseif-else statement.


 See chapter 1 section 1.6.

20

10
Spring 2015

4.4 Conditional Statements

 The x=input(‘prompt’,‘s’) shows the text prompt


and waits for a string input.
response=input('Do you want to continue? Y/N [Y]: ','s');
if (isempty(response))|(response=='Y')|(response=='y')
response='Y'
else
response='N'
end

Do you want to continue? Y/N [Y]: y Do you want to continue? Y/N [Y]: n

response = response =

Y N

>> >>
21

Example 4.4-1
Write a script file to compute the sum of the first 15 terms in the series 5k2 - 2k,
k=1, 2, 3, . . . , 15.

Solution:

22

11
Spring 2015

Example 4.4-1
Write a script file to compute the sum of the first 15 terms in the series 5k2 - 2k,
k=1, 2, 3, . . . , 15.

Solution:

23

Example 4.4-2

24

12
Spring 2015

Example 4.4-2

25

Example
Typing specmat(5) produces
the following matrix:

26

13
Spring 2015

Example 4.4-4
Write a script file to determine how many terms are required for the sum of the series
5k2 - 2k, k = 1, 2, 3, . . . to exceed 10,000. What is the sum for this many terms?

Solution:

27

Example 4.4-4
Write a script file to determine how many terms are required for the sum of the series
5k2 - 2k, k = 1, 2, 3, . . . to exceed 10,000. What is the sum for this many terms?

Solution:

28

14
Spring 2015

Example 4.4-5
Determine how long it will take to accumulate at least $10,000 in a bank account if you
deposit $500 initially and $500 at the end of each year, if the account pays 5 percent
annual interest.

Solution:

29

Example 4.4-5
Determine how long it will take to accumulate at least $10,000 in a bank account if you
deposit $500 initially and $500 at the end of each year, if the account pays 5 percent
annual interest.
Solution:

30

15
Spring 2015

Test Your Understanding

4.5 Loops

 for loops and while loops:


 See chapter section 1.6.

32
20

16
Spring 2015

4.5 Loops
The breakstatement
 It is permissible to use an if statement to “jump” out of the loop
before the loop variable reaches its terminating value. The break
command terminates the loop but does not stop the entire program.

33

4.5 Loops
The continue statement

 The break command stops execution of the loop.

 If we don’t want to execute the case producing an error


but continue executing the loop for the remaining
passes, we can use the continue statement.

34

17
Spring 2015

4.5 Loops
The continue statement

 The continue statement passes control to the next


iteration of the for or while loop, skipping any
remaining statements in the body of the loop.
 The following example uses a continue statement to
avoid computing the logarithm of a negative number.
clear
x=[10,1000,-10,100];
y=NaN*x; y =
for k=1:length(x)
if x(k)<0 1 3 NaN 2
continue
end >>
y(k)=log10(x(k));
end
y

35

4.5 Loops
Using an Array as a loop Index

 It is permissible to use a matrix expression to specify the


number of passes. In this case the loop variable is a
vector that is set equal to the successive columns of the
matrix expression during each pass.
v =

clear 1
A=[1,2;4,5]; 4
for v=A
v
end v =

2
5

36 >>

18

You might also like