Professional Documents
Culture Documents
Lab 2
Lab 2
Lab 2
USED IN LOOPS
length or numel : The functions returns
the total number of elements of the
vector.
‘for’ loop
Syntax:
for var=j:s:k (for i=1:numel(a))
‘code to be executed’
end
‘while’ loop
Syntax:
while (condition is true)
‘code to be executed’
end
IF Statement
Syntax:
if (condition1)
‘code executed if condition1
true’
elseif (condition2)
‘code executed if condition2
true’
elseif(condition3)
‘code executed if condition3
true’
.
.
.
else
== < ‘code executed
> if all above
<= >= ~=
conditions false’
Equal to Less than Greater than Less than &equal to Greater than &equal to Not equal to
end
FOR Loop Example
DIFFERENCE BETWEEN ASSIGNMENT
(=) AND COMPARISON (==) OPERATOR
Assignment (=) operator is used to assign a calculated value or a variable on
the right side to the variable on the left side.
a = 5+4 => means first 5+4=9 is calculated and then assigned to a.
b=a => means b will be equal to a because a is assigned to b.
Now, if a=[1 2 3 4], then b=a+4 => means first calculate a+4 i.e. [5 6 7 8]
and then assign it to b, so b=[5 6 7 8].
Comparison operator is used to compare two variables, arrays, matrices,
alphabets or strings. If the expression on left hand side is equal to the right
hand side then the statement will return 1 otherwise zero.
a==4; ‘a’ is a scalar (variable); statement returns 1 if 4 is stored in ‘a’
otherwise 0.
a==b; ’a’ and ‘b’ both are scalar; returns 1 if ‘a’ equals ‘b’ otherwise 0.
A==B; ‘A’ and ‘B’ are matrices; returns 1 if ‘A’ equals ‘B’ otherwise 0.
R==‘a’; ‘R’ is a character (string) variable and is being compared with
alphabet ‘a’.
UNDERSTANDING HOW
THE CODE WORKS
RAND command
• rand() = generates a random number between
0 and 1 up to 4 digits after decimal point