Session 7 PPT Loop
Session 7 PPT Loop
Content:
• Introduction to MATLAB
• Solution using Loop Programming
Programming
Control Structures
if Statement
if condition,
then-body;
elseif condition,
elseif-body;
else
else-body;
end
clear all
disp ('The Programme gives possible real roots for a Quadratic Equation')
disp ('Input Constants a, b and c for Quadratic Equation a x2 + b x + c =0')
a = input('input value of a');
b = input('input value of b');
c = input('input value of c');
d = b*b-4*a*c;
if d<0
disp ('The roots are not real')
else
Root1 = -b+sqrt(d)/(2*a)
Root2 = -b-sqrt(d)/(2*a)
end
If-else Statement
Programming
Control Structures
switch Statement
switch expression
case label
command-list;
case label
command-list;
...
otherwise
command-list;
end
for statement
continue
Used only inside for or while loops. It skips over the rest of the
loop body, causing the next cycle to begin. Use with care.
Programming
Increment Operators
Increment operators increase or decrease the value of a
variable by 1.
i++ Increment scalar i by 1
i-- Decrement scalar i by 1
A++ Increment all elements of matrix A by 1
v-- Decrement all elements of vector v by 1
For matrices, any and all return a row vector with elements
corresponding to the columns of the matrix.
any(any(C)) Returns 1 if any element of matrix C is non-zero
(e.g. 1)
all(all(C)) Returns 1 if all elements in matrix C are non-
zero (e.g. 1)
Programming
Relational Operators
x < y True if x is less than y
x <= y True if x is less than or equal to y
x == y True if x is equal to y
x >= y True if x is greater than or equal to y
x > y True if x is greater than y
x ~= y True if x is not equal to y
Programming
Boolean Expressions
B1 & B2 Element-wise logical and
B1 | B2 Element-wise logical or
~B Element-wise logical not
salA(1) = 1;
salB(1) = 1.25;
n = 1;
while(salA<salB)
n = n + 1;
end
Final Result: Number of years = 7 (6 years later, i.e., in the 7th year)
Programming- Solution
Code of salary.m (Method 2: Using “for” loop)
salA(1) = 1;
salB(1) = 1.25;
maxYears = 20;
for n=2:maxYears
if (salA(n+1)>salB(n+1) )
break
end
end
Final Result: Number of years = 7 (6 years later, i.e., in the 7th year)
Exercise problem for IF-ELSE
Observed N
Value
NR
Cohessionless
Cohesive Soil
Soil
Nc = 0.77 log10(2000/S)×N No Corrections Required
Above Water
Below Water
Table
N = Nc
NR < 15 NR > 15
N = Nc N = 15 + 0.5 × (Nc - 15)