If statements
One of the most commonly used programming language constructs is the if-construct. With this construct it is possible to decide whether or not to execute certain program lines, based on a relational test of logical variables. The general form of this construct is:
if logical expression
program lines
elseif logical expression
program lines
else
program lines
end
The elseif and else statements are optional, so they can also be omitted. A logical expression is either true or false. In MATLAB, the value 1 is given to a true expression, and the value 0 is given to a false expression. When evaluating logical expressions, we use relational and logical operators given in Table 6.1:
Table 6.1:
Relational operators
| Relational |
|
< |
lower than |
<= |
lower than or equal to |
> |
greater than |
>= |
greater than or equal to |
== |
equal to |
~= |
not equal to |
| |
|
| Logical |
|
& |
and |
| |
or |
~ |
not |
|
Examples:
1 < 2 is true,
1 == 1 is true,
1 == 2 is false,
1 ~= 2 is true
Example 6.4: Write a MATLAB program that simulates the sign function. Use the MATLAB help to see what this function means.
% make a row with time steps
t = -10:0.1:10
% determine the number of time steps in array t with the command size
n = max(size(t))
% initialise the values of f at zero
f = zeros(1,n)
% determine the function values in a FOR loop
for k = 1:n
if t(k) < 0
f(k) = -1;
elseif t(k) == 0
f(k) = 0;
elseif t(k) > 0
f(k) = 1;
end
end
% plot the function
plot(t,f)
Check that, due to the fact that we have initialised f at 0, this if-loop can be simplified.
Example 6.5: Using a for-loop and conditional tests to calculate the inner product of two vectors.
To this end, we write a new function m-file, i.e., we create our own MATLAB command to calculate the inner product. We call our new command inprod. To realise this, we write a new function m-file `inprod.m'. We will call the two vectors we want to multiply in this file
and
. We will call the output argument result.
function result = inprod(a,b)
% test whether the vectors a and b have the sam length
%(otherwise it is not possible to determine the inner product.)
[ra ca] = size(a); % the command size gives the size of the matrix a
% by assigning the number of rows of a to ra
% and the number of columns of a to ca
[rb cb] = size(b);
if ca~=1 % Note, that '~' represents 'not'
error('first argument is not a vector')
end
if cb~=1
error('second argument is not a vector')
end
if ra~=rb
error('vectors cannot be multiplied: they do not have the same length')
end
% initialisation of result (a number)
result = 0;
for p = 1:ra
result = result+a(p,1)*b(p,1);
end
Esteur
2010-03-22