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

Adama Science and Technology

University

Lecture 02: Matlab programming


• Relational and logical operators
• For-end statements
• While-end statement
• If-end statements
• Switch-end statement
1. Relational operator
Relational Operators
Compare two operands and returns 1 if it true,
otherwise returns 0
expr1 op expr2
Operator Description
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal
~= Not equal
1. Relational operator
>> p= 2 < 1.2
p= 0

>> q= 2 ~= pi
q= 1

>> A= [1 2 4;5 2 0]; B= [2 1 0;3 4 0];


>> p= A >= B
p= 0 1 1
1 0 1
1. Relational operator
Example 1: Check whether two roots of ax2 + bx +
c= 0 (a= 1, b= 2, c= 3) are real or not.

>> a= 1; b= 2; c= 3; d= b^2-4*a*c;
>> q= d >= 0 % q= 1 if roots are real
q=
0
>> roots([a b c]) % find roots
ans =
-1.0000 + 1.4142i
-1.0000 - 1.4142i
2. Logical operator
Logical Operation

p q P AND q P OR q NOT p
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
2. Logical operator
Logical Operators
Compare two operands and returns 1 or 0
expr1 op expr2
op expr

Operator Description
& Logical AND
| Logical OR
~ Logical NOT
&& Short-circuit logical AND
|| Short-circuit logical OR
2. Logical operator
expr1 && expr2 : expr2 is not evaluated if expr1= 0
expr1 || expr2 : expr2 is not evaluated if expr1= 1
>> x= 0; y= 1;
>> q= (x~=0) && (y>2)
q=
0
>> p= ~q % Negation of q
p=
1
>> r= (x~=1) || (y>2)
r=
1
2. Logical operator
>> A= [1 2 3 4;5 6 7 8]; A=
1 2 3 4
>> p= (A==5) 5 6 7 8
ans =
0 0 0 0
1 0 0 0
>> (A>3)&(A<=6)
ans =
0 0 0 1
1 1 0 0
3. Operator priority
Operator Priority
Priority Operators
1 ( ) (if nested parentheses exist, inner ones are first)
2 ^, ^, '
3 ~
4 *, /, \, *, /, \
5 +, -
6 :
7 >, <, >=, <=, ==, ~=
8 &
9 | Within each level,
10 operators are evaluated
&&
from left to right.
11 ||
3. Operator priority
>>x= (3/2+2+9*2)^2/20*2
x=
46.2250

Evaluation order
 3/2= 1.5  21.5^2= 462.25
 9*2= 18
 1.5+2= 2.5  462.25/20= 23.1125

 2.5+19= 21.5  23.1125*2= 46.2250


4. Logical function
Logical Functions
TF= any(x) % Returns 1 if any of the elements of x
are nonzero, and 0 otherwise
TF= all(x) % Returns 1 if all the elements of x are
nonzero, and 0 otherwise
TF= isempty(x) % Return 1 if x is an empty array
and 0 otherwise
TF= isequal(x,y) % Returns 1 if x and y are
equivalent and 0 otherwise
TF= isnan(x) % Returns 1 if any of the elements of
x are NaN and 0 otherwise
4. Logical function
TF= isinf(x) % Returns 1 if any of the elements of
x are inf or -inf and 0 otherwise
I= find(x) % Returns the indices of x that point to n
onzero elements. If none is found, returns an empty
matrix

>> x= [-1 0 1 2];


>> TF= any(x) % Returns 1 because there are three nonzeros
TF = 1
>> TF= all(x) % Returns 0 because the second element is zero
TF = 0
4. Logical function
>> buf= []; % Creates an empty array
>> q= isempty(buf) % Returns 1 because buf is an empty array
q= 1
>> str= ''; % Creates an empty string
>> p= isempty(str) % Returns 1 because str is an empty string
p= 1
>> x= [sin(0)/0 cos(0)/0 2]
x=
NaN Inf 2
>> q= isnan(x)
q = 1 0 0 % Returns 1 because the first element of x is NaN
4. Logical function
>> q= isinf(x)
q= 0 1 0 % Returns 1 because the second element of x is inf

>> x= [-1, 5, 0, 7, 9];


>> J= find(x>0) % Returns the indices of elements greater than zero in x
J=2 4 5
>> find(x >0&x<=7) % Returns the indices of elements greater than
zero and less than or equal to 7 in x
ns = 2 4
>> x(find(x ==0))= 10 % Finds the zero elements of x and replaces
them with 10
x = -1 5 10 7 9
4. Logical function
Example 2: Plot y= sin(x)/x (-3  x  3)

>> x= -3*pi:pi/20:3*pi;
>> x(find(x == 0))= eps; % Finds the zero elements of x
and replaces them with eps.
>> y= sin(x)./x;
>> plot(x,y)
5. For-end statement
For-end Statement
% Syntax
for var= s:step:f
statements;
end

var: variable
s: starting value
step: increment
f: upper limit
5. For-end statement
% For example
s= 0; % Initialize s with 0
for i=1:2:6
s= s+i
end

s= 1
s= 4
s= 9
5. For-end statement
Example 3: Calculate 10!= 123…10 using the
for-end statement

facto= 1; % Initialize facto with 1


for i=1:10
facto= facto*i;
end
facto
facto=
3628800
5. For-end statement
Example 4: Write a script that compute the equation
and execute. 10
n
S
n 1 (n  1)(n  2)

s= 0; % Initialize s n= 1:10;
for n=1:10 s= sum(n./(n+1)./(n+2));
s= s+n/(n+1)/(n+2); %s= sum(n./((n+1).*(n+2)))
end s
s

s= s=
1.1865 1.1865
5. For-end statement
Example 5: Write a script that sums all the elements
of a 33 magic matrix.

s= 0; % Initialize s with 0
A= magic(3); [n,m]= size(A);
for i= 1: n
for j= 1: m
s= s+A(i,j);
end
end
s

s= 45
6. While-end statement
While-end Statement
while expression
statements;
end
 statements are repeated while expression is true
count= 0;
while count < 2
count= count+1
end

count= 1
count= 2
6. While-end statement
Example 6: Find the minimum number n such that
1+2+   +n is greater than 50 using the while-end
statement.

n= 1; % Initialize n with 1
while sum(1:n) <= 50
n= n+1;
end
[n sum(1:n)]

ans= 10 55
6. While-end statement
Example 7: Repeat the previous problem using the
while-end and break statements.
count= 1;
while (1)
if count > 10
break;
end
disp(count);
count= count+1;
end

ans= 9 45
7. If-end statement
If-end Statement
if expression
statements;
end
statements are executed if
expression is true
x= pi/4;
if sin(x) >= 0
disp('Yes, true');
end
Yes, true
7. If-end statement
If-else-end Statement
% Syntax
if expression
statement1;
else
statement2;
end

 statement1 is executed if expression is true,


otherwise statement2
7. If-end statement
% For example
x= 2;
if sqrt(x) >= 2
disp('true');
else
disp('false');
end

false
7. If-end statement
Example 8: Find two roots of ax2+bx+c= 0 (a= 1, b=
2, c= 3)

a= 1; b= 2; c= 3; d= b*b-4*a*c;
if d >= 0
x= [-b+sqrt(d); -b-sqrt(d)]/(2*a);
else
x= [-b+j*sqrt(-d); -b-j*sqrt(-d)]/(2*a);
end
x
x= -1.0000 + 1.4142i
-1.0000 - 1.4142i
7. If-end statement
If-elseif-else-end Statement
% Syntax
if expression1
statement1;
elseif expression2
statement2;
else
statement3;
end

 Execute statement1 if expression1 is true, execute


statement2 if expression2 is true, otherwise statement3
7. If-end statement
Example 9: Obtain the value of
x , 0  x  1

f ( x)  1 , 1  x  2 at x= 0.5.
0 , elsewhere

x= 0.5; fx
if x >= 0 && x < 1
fx= x; fx= 0.5
elseif x >= 1 && x < 2
fx= 1;
else
fx= 0;
end
8. Switch-end statement
Switch-end Statement
switch var
case value1
statement1;
case value2
statement2;

otherwise
statementn;
end
8. Switch-end statement
Example 10: Write a script that displays Passed if the
input grade is A~D, displays Failed if F, and warns
Invalid grade if there is no match.
grade= input('Enter grade: ','s'); % Reads a character
switch(upper(grade))
case {'A', 'B', 'C', 'D'}
disp('Passed' );
case 'F'
disp('Failed' );
otherwise
warning('Invalid grade' );
end
8. Switch-end statement
Example 11: Code a program that rolls a die 100 times
and counts the number of occurrences on each side.

rand('seed',123); case 3, n3= n3+1;


n1= 0; n2= 0; n3= 0; case 4, n4= n4+1;
n4= 0; n5= 0; n6= 0; case 5, n5= n5+1;
for i= 1:100 case 6, n6= n6+1;
dice= fix(6*rand+1); end
switch dice end
case 1, n1= n1+1; [n1 n2 n3 n4 n5 n6]
case 2, n2= n2+1;
9. Break, Continue, Return, Pause
Break, continue, return, pause
break % used to terminate the execution of an
iteration loop such as for or while loops when
certain conditions are met.
continue % If continue appears when a condition is
true, it skips to the end of the loop and continues
execution from the next iteration.
return % similar to break or continue except that it
is used primarily within a function.
pause, pause(n) % stops execution for n seconds
before continuing, where n can be any real number.
9. Break, Continue, Return, Pause
% For example
x= 0; alpha= 0.2; eps= 1e-6;
for k=1:50
dfx= 4*(x-1); % calculates f(x)= 4(x-1)
xnew= x-alpha*dfx;
if abs(xnew-x) <= eps
break;
else
x= xnew;
end
end
fprintf('k= %d x= %f\n',k,xnew);
9. Break, Continue, Return, Pause
Example 12: Obtain the function value of f(x)=
xexp(-x) (x= 0, 0.5, 1, 1.5, 2) and display when the
Enter key is pressed.

% For example
for x= 0:0.5:2
fx= x*exp(-x)
pause
end
9. Break, Continue, Return, Pause
Example 13: Write an animation program that draws
the sin(x) graph.

clf
x= 0; h= 0.1; loop= 200; buf= [];
for i= 1:loop
buf= [buf;x sin(x)];
plot(buf(:,1), buf(:,2),'k.-'),
axis([0 h*loop -2 2])
x= x+0.1;
pause(0.01);
end
Q&A

You might also like