5 Programming Big
5 Programming Big
using MATLAB
Dr. Mohammed Hawa
Electrical Engineering Department
University of Jordan
For example
>> x = [6,3,9];
>> y = [14,2,9];
>> x<y
ans =
1 0 0
>> z = x(x<y)
z =
6
z = 5 > 2 + 7
is equivalent to
z = 5 > (2+7)
x = (5 > 2)
>>x = -2:2;
>>k = (abs(x)>1)
k =
1 0 0 0 1
>>z = x(k)
z =
-2 2
>>w = [1,0,0,0,1]; v = x(w)
??? Subscript indices must either be real
positive... integers or logicals.
Copyright © Dr. Mohammed Hawa Electrical Engineering Department, University of Jordan 18
Accessing Arrays Using Logical Arrays
>> 5 && 0
ans =
0
>> [1 2] && [3 4]
??? Operands to the || and && operators must
be convertible to logical scalar values.
Copyright © Dr. Mohammed Hawa Electrical Engineering Department, University of Jordan 21
Order of precedence for operators
Precedence Operator type
First Parentheses; evaluated starting with the
innermost pair.
if logical expression
statements
end
if logical expression
statement group 1
else
statement group 2
end
if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3
end
function y = test(x)
if x >= 9
y = 15*sqrt(4*x) + 10
elseif x >= 0 % already less than 9
y = 10*x + 10
else
y = 10
end
x = [4 -9 25];
if x < 0
disp(’Cant find square root of negative.’)
else
y = sqrt(x)
end
y =
2 0 + 3.000i 5
Copyright © Dr. Mohammed Hawa Electrical Engineering Department, University of Jordan 31
Instead, consider what happens if we test for x positive.
m = 0;
x(1) = 10;
for k = 2:3:11;
m = m + 1;
x(m+1) = x(m) + k^2;
end
for i = 1:1:5
disp(i)
>> loop
1
2
3
4
5
>>
>>number = ’123’
number =
123
x = 5;
while x < 25
disp(x)
x = 2*x - 1;
end
i = 1;
while i^2 <= 50
disp(i^2)
Matlab command prompt
i = i + 1;
>> loop2
end 1
4
9
16
25
36
49
>>
x = [10,1000,-10,100];
y = NaN*x;
for k = 1:length(x)
if x(k) < 0
continue
end
y(k) = log10(x(k));
end
y
switch angle
case 45
disp(’Northeast’)
case 135
disp(’Southeast’)
case 225
disp(’Southwest’)
case 315
disp(’Northwest’)
otherwise
disp(’Direction Unknown’)
end
Copyright © Dr. Mohammed Hawa Electrical Engineering Department, University of Jordan 53
Boolean Variables
• MATLAB allows boolean variables that
take true/false values