You are on page 1of 16

Lab 3

PROGRAMMING IN MATLAB

Logical Operation
Setting logical value:
true, false
Logical Operations:
& (and), | (or), ~ (not), xor, any, all
Relational Operations:
== (eq), ~=(ne), < (lt), > (gt),
<= (le), >= (ge)

Selection Constructs

Three commonly used selection


constructs in MATLAB

1. If-end construct
if condition 1
program 1
end;

Selection Constructs

Three commonly used selection


constructs in MATLAB

2. If-else-end construct
if < condition 1 >
< program 1 >
else
< program 2 >
end;

Selection Constructs

Three commonly used selection constructs in


MATLAB

3. If-elseif-end construct
if condition 1
program 1
elseif condition 2,
program 2
elseif condition 3,
program 3
.
elseif condition N,
program N
end;

Switch Statement
Switch expression
case 1
do these statements
case 2
do these statement
case n
do these statement
end

If loops
Example 1;
A=10;
if A ~= 0
disp(A is not equal to 0)
end

Example of If loop
Example 2;
A=10;
if A > 0
disp(A is positive)
else
disp(A is not positive)
end

Example of If loop
Example 3;
P1 = 3.14;
P2 = 3.14159;
if P1 == P2
disp(P1 and P2 are equal)
else
disp(P1 and P2 are not equal)
end

For loops
Require the following syntax;
for d = array
% command 1
% command 2
% and so on
end

Example of for loops


Example 1;
for d = 0:5
disp(hello)
end

Example of for loops


Example 2;
for a = 10:10:50
for b = 0:0.1:1
disp(hello)
end
end
(Loop a will be executed 5 times. Each time the
outer loop is executed, the inner loop (loop b)
will be executed 11 times, since 0:0.1:1 creates 11
element. Hello will printed 55 times.)

Example of for loops


Example 3;
Frequency is a defining characteristic of many
physical phenomena including sound and
light. The equation of a cosine wave with
frequency f cycles /second is;
Y = cos (2ft)
Create an m-file script to plot the cosine
waveform with frequency values f (cycles/s)
of 0.7, 1, 1.5, and 2 and values of t(s)
between 0 to 4.

Example of for loops


Example 3;
Solution;
t = 0:0.01:4;
for f= [0.7 1 1.5 2];
y = cos(2*pi*f*t);
plot(t,y);
end

While loops
The common syntax;
while condition
statements
end

Example of while loops


Example 1;
n = 10;
while n > 0
disp('Hello')
n = n - 1;
end
(how many times will this loop print the
hello )

You might also like