MATLAB supports the variants of "if" construct:
if ... end
if ... else ... end
if .... elseif ... else ... end
x = 5;
if x > 0
disp('x is positive');
end
x is positive
x = -5;
if x > 0
disp('x is positive');
else
disp('x is negative');
end
x is negative
x = 0;
if x > 0
disp('x is positive');
elseif x < 0
disp('x is negative');
else
disp('x is zero');
end
x is zero
==
(equal to)~=
(not equal to)<
(less than)>
(greater than)<=
(less than or equal to)>=
(greater than or equal to)&
(AND operator)|
(OR operator)~
(NOT operator)x <= 4 & x > 0
means x
is less than or equal to 4 and x
is greater than 0.
Let's look at the basic syntax of the for loop.
for i=[1 3 5 4 10 7]
disp(i);
end
1
3
5
4
10
7
for i=1:10
disp(i)
end
1
2
3
4
5
6
7
8
9
10
The while loop is used to execute a block of code repeatedly as long as the condition is true. Let's look at the basic syntax of the while loop.
i = 1;
while i <= 5
disp(i);
i = i + 1;
end
1
2
3
4
5
i = 1;
while i <= 5
disp(i);
if i == 3
break;
end
i = i + 1;
end
1
2
3
i = 1;
while i <= 5
i = i + 1;
if i == 3
continue;
end
disp(i);
end
2
4
5
6
Let's consider an even problem.
X = 1:10
Y = zeros(1,10)
for i=1:10
if mod(X(i),2) == 0
Y(i) = 1;
else
Y(i) = 0;
end
end
Y
X =
1 2 3 4 5 6 7 8 9 10
Y =
0 0 0 0 0 0 0 0 0 0
Y =
0 1 0 1 0 1 0 1 0 1
S = 0;
for i=1:10
if mod(X(i),3) == 0
S = S + X(i);
end
end
S
S = 18
S = 0;
for x=X
if mod(x,3) == 0
S = S + x;
end
end
S = 18
X
found = 0;
i = 0;
while ~found
i = i + 1
if X(i) == 8
disp('I found it!');
found = 1;
end
end
X =
1 2 3 4 5 6 7 8 9 10
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
I found it!
for i=1:10
fprintf('i = %d\n', i);
if X(i) == 8
disp('I found it!');
end
end
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
I found it!
i = 9
i = 10
for i=1:10
fprintf('i = %d\n', i);
if X(i) == 8
disp('I found it!');
break;
end
end
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
I found it!