Lecture 4
Lecture 4
The if statement in MATLAB allows you to execute code only when a certain condition
is true. It is a fundamental part of controlling program flow.
Example:
x = 5;
if x > 0
disp('x is positive');
end
Output:
x is positive
2. if-else Statement
If the condition is false, the else block runs.
if condition
% Code if true
else
% Code if false
end
Example:
x = -3;
if x > 0
disp('x is positive');
else
disp('x is not positive');
end
Output:
x is not positive
if condition1
% Code if condition1 is true
elseif condition2
% Code if condition2 is true
else
% Code if all conditions are false
end
Example:
x = 0;
if x > 0
disp('x is positive');
elseif x < 0
disp('x is negative');
else
disp('x is zero');
end
Output:
x is zero
4. Nested if Statements
You can place if statements inside other if blocks.
if condition1
if condition2
% Code if both conditions are true
end
end
Example:
x = 10;
y = 5;
if x > 0
if y > 0
disp('Both x and y are positive');
end
end
Output:
Example:
x = 4;
if (x > 2) && (x < 6)
disp('x is between 2 and 6');
end
Output:
x is between 2 and 6
6. Common Mistakes
❌ Using = instead of ==
❌ Missing end
Lab Examples:
A = [1 2 3;
4 5 6;
7 8 9];
%[] delete
A(end, :) = []
A = [1 2 3;
4 5 6;
7 8 9];
x= 5;
if x > 0
disp('x is positive');
disp('x is positive');
disp('x is positive');
disp('x is positive');
end
x=5
if x == 5 % Correct (comparison)
disp('x is 5');
end
x = 2;
if (x > 2) && (x < 6)
disp('x is between 2 and 6');
end
x = -3;
if x > 0
disp('x is positive');
else
disp('x is not positive');
end
x = 0;
if x > 0
disp('x is positive');
elseif x < 0
disp('x is negative');
else
disp('x is zero');
end
x = 10;
y = 5;
if x > 0
if y > 0
disp('Both x and y are positive');
end
end
A = [1, 5, 3, 8];
if any(A > 6) % Checks if any element is > 6
disp('At least one element is greater than 6');
end
B = [2, 4, 5];
if all(B < 6) % Checks if all elements are < 6
disp('All elements are less than 6');
end
v=2:8
if v(mod(v,2)==0)
disp("even")
disp(v(mod(v,2)==0))
end