Sie sind auf Seite 1von 19

1

LESSON OUTCOMES

At the end of this topic, the students will be


able:

To create a simple programming with


Matlab.

To apply the design


programming with Matlab.

structures

in

Outline
1.0 Programming with Matlab
1.1 Relational Operators
1.2 Conditional Statements
1.2.1 if statement

1.2.2 else statement


1.2.3 elseif Statement
1.3 Loop Structures
1.3.1 for loops
1.3.2 while loops
3

1.1 Relational Operators


Result using the relational operator is
0 (false)
1 (true)
MATLAB has six relational operators to make
comparison between arrays.
Relational operator

Meaning

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

==

Equal to

~=

Not equal to

Logical operators [& (and), | (or), ~ (not)]

Exercise
>> x=[6,3,9]
>> y=[14,2,9]
>> z=(x<y)
>> z=(x~=y)
>> z=(x>8)

ans??
ans??
ans??

Can be used for array addressing


>> z=x(x<y)
ans??

Exercise
Arithmetic operators +,-,*,/ and \ have precedence
over the relational operators
>> z=5>2+7
z=??
>> z=5>(2+7) z=??
Parentheses can be used to change the order of
precedence
>> z=(5>2)+7 z=??

1.2 Conditional Statements


MATLAB conditional statements enable us to write
programs that make decisions
Conditional statements contain one or more of the
if
else
elseif

The end statements denotes the end of a


conditional statement, just as the period was used
in the preceding examples.

1.2.1 if statement
Basic form:
if logical expression
statements
end

Exercise
y x

for x 0

>> x=6
y=??
>> x=-4
y=??

1.2.2 else statement


Basic form:
if logical expression
statements group 1
else
statements group 2
end

Exercise
y x

for x 0

y e x 1 for x 0

>> x=4
y=??
>> x=-9
y=??

1.2.3 elseif Statement


Basic form:
if logical expression 1
statements group 1
elseif logical expression 2
statements group 2
else
statements group 3
end

Exercise
y ln x

for x 10

y x

for 0 x 10

y e x 1 for x 0

>> x=20
y=??
>> x=5
y=??
>> x=-4
y=??

1.3 Loop Structures


A loop is a structure for repeating a calculation a
number of times.
Two types of explicit loops:
for loop
when the number of passes is known ahead
of time
while loop
when the looping process must terminate
when a specified condition is satisfied
The number of passes is not known in
advance

1.3.1 for loops


Typical structure of a for loop :
for loop variable = m:s:n
statements
end

Example
Start

for k= m:s:n
statements
end

Set k = m

k>
n?

Increment k
by s

False

Statement
s
End

Statement
s following
the End
statement

True

Exercise

1.3.2 while loops


Typical structure of a while loop :

while logical expression


statements
end

Start
Logical
Expressio
n
True

Statements
(which increment
the loop variable)

End

Statements
following the
End statement

False

Example
5
9
17

1
2
3
4

Das könnte Ihnen auch gefallen