SAAAAANI
Programming With MATLAB
Program Design and Development
• 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.
Program Design and Development
Algorithms and Control Structures
•An Algorithm is an ordered sequence of precisely defined
instructions that perform 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 operation :
•Sequential operations. These are instructions that are executed in
order.
•Conditional operations. These are 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). These are control structures that repeat
the execution of a block of instructions.
STRUCTURE CHART and FLOWCHART
• 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 problem 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 wIth out showing
the detail of the calculations and decision processes.
STRUCTURE CHART and FLOWCHART
A) Structure chart
•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.
STRUCTURE CHART and FLOWCHART
• Two types of charts aid in developing structured programs and in
documenting them.
• These are structure charts and Flowcharts.
B) Flowcharts
• Are useful for developing and documenting
programs that contain conditional
statement, 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 if
statement is shown in Figure 4. 1-2.
• Flowcharts use the diamond symbol to
indicate decision points.
Pseudocode
• 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 pseudocode, in which natural language and
mathematical expressions are used to construct statements that look like
computer statements but without detailed syntax.
• Pseudocode may also use some simple MATLAB syntax to explain the
operation of the program.
Finding Bugs
• Debugging a program is the process of finding and removing the
"bugs," or “errors” in a program.
• Such error usually fall into one of the following categories.
• 1. Syntax errors such as omitting a parenthesis or comma, or spelling
a command name incorrectly. MATLAB usually detect the more
obvious errors and displays a message describing the error and its
location.
• 2. Runtime errors. Errors due to an incorrect mathematical
procedure. These are called runtime errors. They do not necessarily
Occur every time the program is executed; their occurrence often
depend on the particular input data.
• A common example is division by zero.
Relational Operators
• MATLAB has six relational operators to make comparisons
between arrays.
• These operators are shown in Table 4.2-1
• The “equal to” operator consists of two = signs, not a ingle =
sign as you might expect.
• The single = sign is the assignment, or replacement Operator
in MATLAB.
Relational Operators and Logical Variables
• The result of a comparison using the relational operators is a
logical value, either 0 (if the comparison is False) or 1 (if the
comparison is True).
• For example:
• x = 2 and y = 3
>> x = 2 ; y = 3
>> z = x > y
>> z = 0
• Similarly
>> z = x ==y
>> z = 0
Relational Operators and Logical Variables
• When used to compare arrays, the relational operators
compare the arrays on an element-by-element basis.
• The arrays being compared must have the same dimension.
• The only exception occurs when we compare an array to
scalar number , in that case all the elements of the array are
compared to the scalar.
• For Example:
• x= [1 2 4 0 1], y = [ 0 0 1 5 9]
>> x= [1 2 4 0 1] ; y = [ 0 0 1 5 9]
>> z = x < y
>> z = 0 0 0 1 1
Relational Operators and Logical Variables
Find Function
•The function find (x) computes an array containing the indices of the
non zero elements of the numeric array x.
•For example,
•x= [-2 , 0 , 4];
•y = find (x )
•y = 1 3
•The resulting array y = [1 , 3 ] indicates that the first and third elements
of x are nonzero.
•The find function returns the indices, not the values.
•To show Value
z = x ( x ~= 0 )
z= [-2 4]
Logical expressions
Relational operators (compare arrays of same sizes)
== (equal to) ~= (not equal)
< (less than) <= (less than or equal to)
> (greater than) >= (greater than or equal to)
Logical operators (combinations of relational operators)
& (and)
| (or)
~ (not)
X=input(’enter
X=input(’enter the
the values
values of
of
input
input x:’)
x:’)
if
if (x>=0)
(x>=0) && (x<=10)
(x<=10)
disp(‘x
disp(‘x is
is in
in range
range
[0,10]:’)
[0,10]:’)
else
else
disp(‘x
disp(‘x is
is out
out of
of range:’)
range:’)
Assignment
Example 1.6-4 page 45
Conditional Statements
• The MATLAB conditional statements allow us to write
programs that make decisions.
• Conditional statements contain one or more of the if,
else, and else if statements.
• The end statement denotes the end of a conditional
statement.
• These conditional statements read somewhat like their
English language equivalents.
Conditional Statements
A) The if Statement
Syntax:
if logical expression
Start
statements
end
If x>=0
Example:
True
if x >= 0 False
y = sqrt (x) y = sqrt(x)
end
OR
end
if x >= 0 , Y = sqrt(x) , end
Flow Chart of If Statement
Conditional Statements
if Statement
•The logical expression may be a compound
expression i.e the statements may be a ingle
command or a series of commands separated by
commas or semicolons or on separate lines.
Example:
z = O; w = 0 ;
if (x >= O) & (y >= 0)
z = sqrt(x) + sqrt(y)
w = log(x) - 3*log(y)
End
Conditional Statements
if Statement
We may "nest" if statements, as shown by the following example.
if logical expression I
statement group 1
if logical expression 2
statement group 2
end
End
Note that each if statement has an accompanying end statement.
Conditional Statements
B) The else Statement
When more than one action can occur as a result of a decision, we can use
the “else” and “elseif” statements along with the if statement.
Syntax: Start
if logical expression
statement group J
else False
statement group 2 If x>=0
end
True
Example:
if x >= 0 y = sqrt(x) y = exp(x) - 1
y = sqrt (x )
else
y = exp (x) - 1
end
end
Flow Chart of else Statement
Conditional Statements
The else Statement
if logical expression, is performed, where the logical expression
may be an array, the test returns a value of true only if ALL the elements of
the logical expression are true.
Example
x = [4 ,- 9,25);
if x < 0
disp ( ' Some of the elements of x are negative .' )
else
y = sqrt (x)
end
x = [-4 ,- 9,-25);
if x < 0
disp ( ' Some of the elements of x are negative .' )
else
y = sqrt (x)
end
Conditional Statement
Example
Conditional Statements
C) The elseif Statement Start
Syntax:
if logical expression 1
statement group 1 logical
False
exp 1
elseif logical expression 2
statement group 2 True False
logical
exp 2
else Statement 1
statement group 3 True
end
Statement 2 Statement 3
end
Flow Chart of else Statement
Conditional Statements
The elseif Statement
Example:
Example:
if logical expression if
if height
height >> 170
170
commands disp(’tall’)
disp(’tall’)
elseif logical expression elseif
elseif height<150
height<150
commands> disp(’small’)
disp(’small’)
else else
else
commands disp(’average’)
disp(’average’)
end end
end
Conditional Statements
Start
False
X>10
True False
X>=0
y = log(x)
True
y = sqrt(x) y = exp(x) - 1
end
Flow Chart of else Statement
Conditional Statements
Example:
To find Even and odd number
x=input('Enter the No=');
if mod(x,2)==0
disp('Even Number')
else
disp('Odd No')
end
Conditional Statements
Example:
clear
N = input('Give numerator: ');
D = input('Give denominator: ');
if D==0
'Sorry, cannot divide by zero‘
else
ratio = N/D
end
Conditional Statements
Example:
clear
month = input('Give month number (1-12): ' );
if month==1 | month==3 | month ==5 | month==7 | month==10 | month==12
'Your month has 31 days‘
elseif month==2
'Your month has 28 days‘
else
'Your month has 30 days‘
end
end
Iterative operations / Loops
• A loop is a Structure for repeating a calculation a number of
times.
• Each repetition of the loop is a pass.
• MATLAB uses two types of explicit loops:
a) for loop:
when the number of passes is known ahead of time.
b) while loop:
when the looping process must terminate when a specified
condition is satisfied, and thus the number of passes is not
known in advance.
Loops
a) for Loops:
The typical structure /syntax of a for loop is
• The expression m:s:n assigns an
for loop variable = m:s:n
initial value of m to the loop
statements variable, which is incremented by
end the value s called the step value or
incremental value.
Example: • The statements are executed once
during each pass, using the current
for k = 5 : 10 : 35 value of the loop variable.
x = k ^2 • The looping continues until the loop
End variable exceeds the terminating
OR value n .
for k = 5 : 10 : 35, x = k ^2,end
Loops
a) for Loops:
Example: Generate a matrix
for i = 1:2
for j = 1:6
H(i,j) = 1/(i+j);
end
End
>>H
H=
0.5000 0.3333 0.2500 0.2000 0.1667 0.1429
0.3333 0.2500 0.2000 0.1667 0.1429 0.1250
Loops
b) while Loops:
•The while loop is used when the looping process terminates
because a specified condition is satisfied, and thus the number
of passes is not known in advance.
Start
Syntax
while logical expression False
Log
statements exp
end
True
Example:
Statement
x=5; Which
increment the
while x < 25 loop variable
disp (x)
x = 2*x - 1;
end
end
Flow Chart of while loop
Loops
b) while Loops: Start
Example:
x=1; False
while x ~= 5 Log
exp
disp (x)
x = x +1; True
end Statement
Which
increment the
loop variable
end
Flow Chart of while loop
The switch Structure
• The switch structure provides an alternative to using the if,
elseif, and else commands.
• Anything programmed using switch can also be programmed
using if structures.
• However, for some applications the switch structure is more
readable than code using the if structure.
Syntax:
switch input expression (scalar or string)
case value1
statement group 1
case value2
statement group 2
otherwise
statement group n
end
The switch Structure
• Example:
Angle=input(‘Enter Angle’)
switch Angle
case 45
disp ( ' Northeast' )
case 135
disp ( ' Southeast' )
case 225
disp ( ' Southwest ' )
case 315
disp ( 'Northwes t ' )
otherwise
disp ( ' Direction Unknown ' )
end
The switch Structure
• Example:
switch angle
case {0 ,360}
disp ( 'North ' )
case {-180 ,180}
disp ( ' South ' )
case {-270 , 90}
disp( ' East ' )
case {-90 , 270}
disp( ' West ' )
otherwise
disp ( ' Direction Unknown ' )
end
The switch Structure
• Example:
if A > B | switch grade
'greater‘ | case 0
elseif A < B | ‘Excellent’
'less‘ | case 1
elseif A == B | ‘Good’
'equal‘ | case 2
else | ‘Average’
error('Unexpected situation') | otherwise
end | ‘Failed’
| end