LECTURE 4: PROGRAMMING WITH
M AT L A B ( PA R T 1 )
1
2
CONTENTS
Program Design and Development
Algorithms and Control Structures
Structured Programming
Advantages of Structured programming
Top-Down Design
Program Documentation
Relational Operators and Logical Variables
Logical Operators and Functions
Conditional Statements
Examples & Practice
ALGORITHMS AND CONTROL
3
STRUCTURES
An algorithm:
An ordered sequence of precisely defined instructions that performs some task in a finite amount of
time.
must have ability to alter the order of its instructions using a control structure.
Algorithm operations: sequential operations, conditional operations, iterative operations (loops)
Sequential operations: executed in order.
Conditional operations: first ask a question to be answered with a true/false answer and the
select the next instruction based on the answer.
Iterative operations (loops): repeat the execution of a block of instructions
4
STRUCTURED PROGRAMMING
Structured programming:
A technique for designing programs using hierarchy of modules, each having a single entry and single
exit point.
Control is passed downward through the structure without unconditional branches to higher levels of
the structure.
Modules in Matlab can be built-in or user-defined functions
5
A D VA N T A G E S O F S T R U C T U R E D P R O G R A M M I N G
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 the 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
11/17/2021
TOP-DOWN DESIGN
4. Work through the solution steps by hand or with a
Top-down design:
calculator; use a simple set of data if necessary.
A method for creating structured programs
Describe a program’s intended purpose at a very high 5.Write and run the program.
level initially 6.Check the output of the program with your hand
Process of top-down design: solution.
1. State the problem concisely. 7.Run the program with input data and perform a reality
2. Specify the data to be used by the program. This is check on the output.
“input”. If the program is used as a general tool in the future, test
3. Specify the information to be generated by the it by running it for a range of reasonable data values;
perform a reality check on the results.
program. This is “output”.
6
7
P R O G R A M D O C U M E N TAT I O N ( I )
Program documentation: is aided by structured charts and flow charts.
Structured charts:
A graphical description showing how the different parts of the program are connected together.
Be useful in the initial stages of top-down design.
Displays the organization of a program without showing the details of the calculations and decision
process.
Show the connection between the main program and the modules.
Be limited by their size.
8
P R O G R A M D O C U M E N TAT I O N ( I I )
Structure chart of a game program
Main Program
Player input Game Status Strategy
Program Display Program Program
o Player input Program: allows the human player to input a move.
o Game Status Display Program: updates and displays the game grid.
o Strategy Program: contains the computer’s strategy for selecting its movies.
9
P R O G R A M D O C U M E N TAT I O N ( I I I )
Flowcharts: Flowchart representation of the if statement
Being used in the programs containing the
Start
conditional statements.
Display the various paths (called “branches”)
Logical False
that a program can take. Expression
Use diamond symbol to indicate decision
True
points.
Being limited by their size. Statements
End
10
P R O G R A M D O C U M E N TAT I O N ( I V )
Pseudocode:
Used to avoid dealing immediately with the possibly complicated syntax of the programming
language.
Uses natural language and mathematical expressions to construct statements that look like computer
statements but without detailed syntax.
Use some simple Matlab syntax to explain the operation of the program.
Be an imitation of the actual computer code.
Useful for outlining a program before writing the detailed code.
11
P R O G R A M D O C U M E N TAT I O N ( V )
Finding Bugs
Debugging program is the process of finding and removing the “bugs” or errors, in a program. Such
errors include:
Syntax errors (omitting a parenthesis, comma, spelling a command name incorrectly) Matlab
displays the errors and its location.
Errors due to an incorrect mathematical procedure (runtime errors). They do not occur every time,
depend on the particular input data. (Ex: division by zero).
12
S E Q U E N T I A L O P E R AT I O N S
Compute
the perimeter and the area of a triangle whose sides are . The formulas are:
1. Enter the side lengths , and .
2. Compute the perimeter .
3. Compute the semi-perimeter .
4. Compute the area .
5. Display the results and .
6. Stop
13
S E Q U E N T I A L O P E R AT I O N S ( C O N T. )
The program is:
a=input('Enter the value of side a: ');
b=input('Enter the value of side b: ');
c=input('Enter the value of side c: ');
p=a+b+c;
s=p/2;
A=sqrt(s*(s-a)*(s-b)*(s-c));
disp('The perimeter is: ')
p
disp('The area is: ')
A
14
C O N D I T I O N A L O P E R AT I O N ( C O N T. )
Given
the coordinates of a point, compute its polar coordinates , where
1. Enter the coordinates and .
2. Compute the hypotenuse
3. Compute the angle
3.1. If :
3.2. Else:
4. Convert the angle to degrees.
5. Display the results and .
6. Stop
15
C O N D I T I O N A L O P E R AT I O N S ( C O N T. )
The program is: x=input('Enter the value of x: ');
y=input('Enter the value of y: ');
r=sqrt(x^2+y^2);
if x>=0
theta=atan(y/x);
else
theta=atan(y/x)+pi;
end
disp('The hypoteneuse is: ')
disp(r)
theta=theta*180/pi;
disp('The angle in degrees is: ')
disp(theta)
R E L AT I O N A L O P E R AT O R S A N D L O G I C A L
16
VA R I A B L E S
Relational operators are used to compare arrays
Relational operator Meaning
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
17
>> z=(x>y)
z=
0 0 0
>> x=[2 3 6];
>> y=[5 3 8]; >> z=(x>=y)
>> z=(x<y) z=
z= 0 1 0
1 0 1 >> z=(x==y)
z=
>> z=(x<=y)
0 1 0
z=
>> z=(x~=y)
1 1 1 z=
1 0 1
L O G I C A L O P E R AT O R S A N D F U N C T I O N S
18
(I)
Logical operators
Operator Name Definition
~ NOT ~A returns an array the same dimension as A; the new array has ones where
A is zero and zeros where A is nonzero.
A & B returns an array the same dimension as A and B; the new array has
& AND ones where both A and B have nonzero elements and zeros where either A
or B is zero.
A|B returns an array the same dimension as A and B; the new array has
| OR ones where at least one element in A or B is nonzero and zeros where A and
B are both zero.
&& Short-Circuit AND Operator for scalar logical expressions. A&&B returns true if both A and B
evaluate to true, and false if they do not.
Operator for scalar logical expressions. A| |B returns true if either A or B or
|| Short-Circuit OR both evaluate to true, and false if they do not.
19
L O G I C A L O P E R AT O R S A N D F U N C T I O N S ( I I )
Order of precedence for operator types
Precedence Operator type
First Parentheses; evaluated starting with the innermost pair.
Second Arithmetic operators and logical NOT (~); evaluated from left to right.
Third Relational operators; evaluated from left to right.
Fourth Logical AND.
Fifth Logical OR.
20
EXAMPLE 1
x=[6,3,9] ; y=[14,2,9] ;
z=0&3
x=[1 3 5] ; y=[0 -2 5] a=[4,3,12]
z=2&3
1. z=~x 1. z=(x>y)&a
z=0&0
2. u1=~x>y 2. z=(x>y)&(x>a)
z=[5,-3,0,0] & [2,4,0,5]
3. u2=(~x)>y 3. z=x>y&x>a
z=1&2+3
4. u3=~(x>y) z=1&(2+3) z=[5,-3,0,0]|[2,4,0,5]
5. u4=(x<=y) z=5<6&1 z=3<5|4==7
z=(5<6)&1 z=1|0&1
z=1|0&0
z=0&0|1
z=~3==7|4==6
21
L O G I C A L O P E R AT O R S A N D F U N C T I O N S ( I I I )
find function
find() computes an array containing the indices (not values) of the nonzero elements of the array .
Examples:
x=[5,-3,0,0,8] ; y=[2,4,0,5,7]
>>z=find(x&y)
>>values=y(x&y)
>>how_many=length(values)
22
C O N D I T I O N A L S TAT E M E N T S ( I )
The if statement
if logical expression 1
if logical expression if logical expression 2
statements statements
end end
end
Ex: y x Can be replaced by
if x>=0 if logical expression 1&2
y=sqrt(x) statements
end end
23
EXAMPLE 2
z=0; w=0;
x,y
if (x>=0) & (y>=0)
False
x>=0?
z= sqrt(x)+sqrt(y)
w=log(x)-3*log(y) True
False
end y>=0?
The values of z and w are computed
True
only if both x and y are nonnegative.
Compute z,w
Otherwise, z and w retain their
values of zero.
Flow chart corresponding to the pseudocode example End
24
C O N D I T I O N A L S TAT E M E N T S ( I I )
The else statement
Start
if logical expression 1 Logical
False
statement group 1 expression
else
statement group 2 True
end
Statement Statement
group 1 group 2
Flow chart of the else structure
End
25
EXAMPLE 3
Start
Suppose that for and for
False
x>=0 ?
if x>=0 True
y=sqrt(x)
else
y=exp(x)-1 y=sqrt(x) y=exp(x)-1
end
End Flow chart
26
U S E I F W I T H T H E A R R AY
True if all of
Consider the following statements elements
of x <0
x = [ 4 -9 16]
if x<0
disp (‘Some of elements of x are negative.’)
else
y = sqrt (x)
end
When this program is run, it gives the result
y=2 0+3.000i 4
11/17/2021
27
U S E I F W I T H T H E A R R AY
Consider the following statements
x = [ 4 -9 16] True if all of elements
of x >=0
if x>=0
y = sqrt (x)
else
disp (‘Some of elements of x are negative.’)
end
When this program is run, it gives the result
Some of elements of x are negative.
28
C O N D I T I O N A L S TAT E M E N T S ( C O N T. )
The elseif statement if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3
end
Notes:
else and elseif can be omitted if not required.
If both are used, else statement must come after elseif statement to take care of all conditions
that might be unaccounted for.
elseif does not require a separate end statement.
29
Start
Logical False
expressio
n1
True
Statement False
Logical
group 1
expression 2
True
Statement Statement
group 2 group 3
End Flow chart of the general if structure
30
EXAMPLE 4
Suppose that x5
ln x if
y
x if 0 x5
if x>=5
y=log(x)
if x>=5
else
y=log(x)
if x>=0
elseif x>=0
y=sqrt(x)
y=sqrt(x)
end
end
end
31
EXAMPLE 5
Suppose that ln x if x 10
y x if 0 x 10
e x 1 if x0
if x>10
y=log(x)
elseif x>=0
y=sqrt(x)
else
y=exp(x) - 1
end
32
PRACTICE
Given
1. the first order equation: .
Write the program to find its root. Suppose that and are optional inputs.
2. Given the second order equation: .
Write the program to find its roots. Suppose that , and are optional inputs.
11/17/2021