Conditional statements are examples of "branching behavior", and they allow your code to perform different tasks depending on certain conditions.
There are a few different forms:
An if statement allows a block of code
to be executed only when certain conditions hold.
if a < 10
b = 1
end
if statement starts with the "if" keyword.if.end"An if block can include alternate choices.
if a < 10
b = 1
else
b = 2
end
An if block can include multiple choices.
if a < 10
b = 1
elseif a < 20
b = 2
else
b = 3
end
Multiple logical expressions can be combined together using logical operators.
&&||~
if (a > 3) && (a < 10)
b = 1
end
Read the following code and explain what it does.
M = magic(5);
for i = 1:5
for j = 1:5
if M(i,j) < 4
M(i,j) = 0;
elseif M(i,j) < 6
M(i,j) = 1;
else
M(i,j) = 2;
end
end
end
magic(5) that are less than 10 / greater than 20.
Can you recreate this image using "for" and "if"?
What about this?