% less than
format compact
x = 2;
y = -2;
x < y % test if x is smaller than y (0 is flase, 1 is true)
ans = 0
% greater than
y > x
ans = 0
% for vectors
x = [-1 2 0 4 6];
y = [2 1 -1 5 9];
x > y % evaluates each element
ans = 0 1 1 0 0
% less-than or equal to
x <= y
ans = 1 0 0 1 1
% greater-than or equal to
x >= y
ans = 0 1 1 0 0
% equal to
x == y
ans = 0 0 0 0 0
& AND
~ NOT
| OR
XOR Exclusive OR
x = [1 0 1 1 0 0];
y = [0 1 0 1 0 1];
% AND
x & y
ans = 0 0 0 1 0 0
% NOT
~x
ans = 0 1 0 0 1 1
% OR
x | y
ans = 1 1 1 1 0 1
% if statements are handled much the same as any other language
clear all
x = 3;
if x < 4
disp('Hello World!!')
disp(x)
end
Hello World!! 3
% same goes for if-else
if x > 0
y = log(x)
else
disp('Log args can not be <= zero!')
end
y = 1.0986
x = -3;
if x > 0
y = log(x)
else
disp('Log args can not be <= zero!')
end
Log args can not be <= zero!
% we can also output an audible alert using 'beep'
if x > 0
y = log(x)
else
beep
disp('Log args can not be <= zero!')
end
Log args can not be <= zero!
clear all
age = 37;
if age < 16
disp('You are too young to apply!')
elseif age < 18
disp('You can apply for a learners permit')
elseif age < 70
disp('Youre good to go!!!')
else
disp('You need a provisional license')
end
Youre good to go!!!
% simple example
clear all
k = 0;
while k < 3
k = k +1;
end
disp(k)
3
% here is a simple for loop
for i = [1 2 3]
i
end
i = 1 i = 2 i = 3
% the variable i is now 3
i
i = 3
% another example
for k = 0:8
2^k
end
ans = 1 ans = 2 ans = 4 ans = 8 ans = 16 ans = 32 ans = 64 ans = 128 ans = 256
% another example
v = [1:3:10]
for j = 1:4
v(j) = j;
end
v
v = 1 4 7 10 v = 1 2 3 4
The previous example illustrates how a for loop works, but it is not the most efficient manner in which to iterate through a matrix an perform calculations on each element.
% this is the preferred manner
clear all
A = [[1 2 3]' [3 2 1]' [2 1 3]']
A = 1 3 2 2 2 1 3 1 3
B = A;
for j = 2:3
A(j,:) = A(j,:) - A(j-1,:)
end
A = 1 3 2 1 -1 -1 3 1 3 A = 1 3 2 1 -1 -1 2 2 4
clear all
scores = [30 65 90 87 56 34 82 99 90];
count = 0;
for k = 1:length(scores)
if scores(k) > 50
count = count + 1;
end
end
disp(count)
7