Lab 3 numerical method
-
Upload
cahaya-fitrahku -
Category
Documents
-
view
237 -
download
1
Transcript of Lab 3 numerical method
-
7/28/2019 Lab 3 numerical method
1/16
Lab 3
PROGRAMMING IN MATLAB
-
7/28/2019 Lab 3 numerical method
2/16
Logical Operation
Setting logical value:
true, false
Logical Operations:
& (and), | (or), ~ (not), xor, any, all
Relational Operations:
== (eq), ~=(ne), < (lt), > (gt),
= (ge)
-
7/28/2019 Lab 3 numerical method
3/16
Selection Constructs
Three commonly used selectionconstructs in MATLAB
1. If-end construct
if condition 1
program 1
end;
-
7/28/2019 Lab 3 numerical method
4/16
Selection Constructs
Three commonly used selectionconstructs in MATLAB
2. If-else-end construct
if < condition 1 >
< program 1 >
else
< program 2 >
end;
-
7/28/2019 Lab 3 numerical method
5/16
Selection Constructs
Three commonly used selection constructs in
MATLAB
3. If-elseif-end construct
if condition 1
program 1elseif condition 2,
program 2
elseif condition 3,
program 3.
elseif condition N,
program N
end;
-
7/28/2019 Lab 3 numerical method
6/16
Switch Statement
Switch expression
case 1
do these statements
case 2
do these statement
case n
do these statement
end
-
7/28/2019 Lab 3 numerical method
7/16
If loops
Example 1;
A=10;
if A ~= 0
disp(A is not equal to 0)
end
-
7/28/2019 Lab 3 numerical method
8/16
Example of If loop
Example 2;
A=10;
if A > 0
disp(A is positive)
else
disp(A is not positive)
end
-
7/28/2019 Lab 3 numerical method
9/16
Example of If loop
Example 3;
P1 = 3.14;
P2 = 3.14159;if P1 == P2
disp(P1 and P2 are equal)
elsedisp(P1 and P2 are not equal)
end
-
7/28/2019 Lab 3 numerical method
10/16
For loops
Require the following syntax;
for d = array
% command 1
% command 2
% and so on
end
-
7/28/2019 Lab 3 numerical method
11/16
Example of for loops
Example 1;
for d = 0:5
disp(hello)
end
-
7/28/2019 Lab 3 numerical method
12/16
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 theouter loop is executed, the inner loop (loop b)will be executed 11 times, since 0:0.1:1 creates 11element. Hello will printed 55 times.)
-
7/28/2019 Lab 3 numerical method
13/16
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 withfrequency f cycles /second is;
Y = cos (2ft)
Create an m-file script to plot the cosinewaveform with frequency values f (cycles/s)of 0.7, 1, 1.5, and 2 and values of t(s)between 0 to 4.
-
7/28/2019 Lab 3 numerical method
14/16
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
-
7/28/2019 Lab 3 numerical method
15/16
While loops
The common syntax;
while condition
statements
end
-
7/28/2019 Lab 3 numerical method
16/16
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 )