Back to tutorial index

Logical operators and conditional statements


Topics in this lab

Introduction

Back to the top

Logical operators

Another key concept in programming is the ability to test a conditional statement and make decisions about the flow of the program based on the truth value of the statement. Examples of such statements are "Is A equal to B?" or "Is A less B?" We can also ask compound conditionals such as "Is A < B and C < B?" Or "Is A > B or C > B?".

To formulate the above questions, we will use binary operators that take two arguments ('A' and 'B') in the above examples and returns a value of "true" or "false". In Matlab, "true" is integer 1 and "false" is the integer 0. The binary operators that we will find use in comparing numeric values are called "relational operators", and are given here.

>> help relop
 Relational operators.
  < > Relational operators.
      The six relational operators are <, <=, >, >=, ==, and ~=.
      A < B does element by element comparisons between A and B
      and returns a matrix of the same size with elements set to logical
      1 (TRUE) where the relation is true and elements set to logical 0
      (FALSE) where it is not.  A and B must have the same dimensions
      (or one can be a scalar).
.................
  &   Element-wise Logical AND.
      A & B is a matrix whose elements are logical 1 (TRUE) where both A
      and B have non-zero elements, and logical 0 (FALSE) where either has
      a zero element.  A and B must have the same dimensions (or one can
      be a scalar).
................
  |   Element-wise Logical OR.
      A | B is a matrix whose elements are logical 1 (TRUE) where either
      A or B has a non-zero element, and logical 0 (FALSE) where both have
      zero elements.  A and B must have the same dimensions (or one can
      be a scalar).
...............
  ~   Logical complement (NOT).
      ~A is a matrix whose elements are logical 1 (TRUE) where A has zero
      elements, and logical 0 (FALSE) where A has non-zero elements.
...............
  xor Exclusive OR.
      xor(A,B) is logical 1 (TRUE) where either A or B, but not both, is
      non-zero.  See XOR.

Here are some simple examples illlustrating the use of relational (or "logical") operators.

true
ans =

     1

false
ans =

     0

x = 5;
disp(x > 6)
     0

disp(x < 10 & x < 6)
     1

disp(x > 0 | x < -1);
     1

disp(xor(x < 10,x > -1));
     0

disp(xor(x < 10, x < 0));
     1

disp(x < 10 | x < 20);
     1

disp(x > 10 | false);
     0

disp(x < 10 & true);
     1

Back to the top

Using logical operators with arrays

These relational tests, when used with Matlab arrays, produce another array whose entries are '0' where the relational test is false, and '1' where the relational statement is true. For example,

format short
x = -1 + 2*rand(1,7)  % Random numbers between -1 and 1.
x =

   -0.5884   -0.1858    0.4302    0.9184   -0.2761   -0.9148    0.9526

x > 0
ans =

     0     0     1     1     0     0     1

x < 0
ans =

     1     1     0     0     1     1     0

These 0-1 arrays in turn can be used to index into the original array and mask certain elements. For example, we can pull out only the positive entries of x :

m = x > 0;
x(m)
ans =

    0.4302    0.9184    0.9526

Or, we can pull out only the negative entries of x :

m = x < 0;
x(m)
ans =

   -0.5884   -0.1858   -0.2761   -0.9148

We can use this array to selectively set entries in x to different values depending on the masking array.

m = x > 0;
x(m) = 10;

m = x < 0;
x(m) = -10;

disp(x)
   -10   -10    10    10   -10   -10    10

We can shorten the above by simply writing

x = -1 + 2*rand(1,7);
y = 10*(x > 0) + -10*(x < 0);
fprintf('%8.2f',x);
fprintf('\n');
fprintf('%8.2f',y);
fprintf('\n');
   -0.50    0.81    0.35   -1.00   -0.73    0.19   -0.84
  -10.00   10.00   10.00  -10.00  -10.00   10.00  -10.00

Back to the top

Conditional statements

Where these logical statements become useful is when they can be used to control the flow of a program. For example, suppose you wanted to divide one number by another number. You might first check to see that the divisor is not equal to 0.

a = 5;
b = 0;
if (b ~= 0)
  c = a/b;
else
  fprintf('Cannot divide by 0\n');
end;
Cannot divide by 0

A more complex if-else statement can be written like this. In this example, we find two random numbers between -1 and 1. We then check to see if either number is in [-1/3, 1/3] and if so, set the value to 0. We then use if-else statements to find whether a, b or both are positive, negative or equal to 0.

% A rather long way to find the sign of two numbers... (:-))
a = -1 + 2*rand(1,1);
b = -1 + 2*rand(1,1);
a(abs(a) < 1/3) = 0;   % a or b will be zero 1/3 of the time.
b(abs(b) < 1/3) = 0;
if (a*b < 0)
    % Either a < 0 or b < 0, but not both
    if (a < 0)
        fprintf('a < 0\n');
        fprintf('b > 0\n');
    else
        fprintf('a > 0\n');
        fprintf('b < 0\n');
    end
elseif (a*b > 0)
    % Both a > 0 and b > 0, or a < 0 and b < 0
    if (a < 0)
        fprintf('a < 0\n');
        fprintf('b < 0\n');
    else
        fprintf('a > 0\n');
        fprintf('b > 0\n');
    end;
else
    % Either a == 0, b == 0 or both.
    if (xor(a == 0, b == 0))
        if (a ~= 0)
            if (a > 0)
                fprintf('a > 0\n');
            else
                fprintf('a < 0\n');
            end;
            fprintf('b == 0\n');
        else
            fprintf('a == 0\n');
            if (b > 0)
                fprintf('b > 0\n');
            else
                fprintf('b < 0\n');
            end;
        end;
    else
        fprintf('a == 0\n');
        fprintf('b == 0\n');
    end;
end;
fprintf('a = %f\n',a);
fprintf('b = %f\n',b);
a < 0
b == 0
a = -0.888270
b = 0.000000

Notice that we did not include any statements checking whether x was exactly equal to another number. The following demonstrates why such a test might not always give you what you expect.

x = cos(pi/3);
if (x == 0.5)
    fprintf('cos(pi/3) == 0.5\n');
else
    fprintf('cos(pi/3) is not exactly 0.5!\n');
end;

fprintf('cos(pi/3) is very close to 0.5, but not exactly 0.5\n');
fprintf('abs(cos(pi/3) - 0.5) = %16.8e\n',abs(x-0.5));
cos(pi/3) is not exactly 0.5!
cos(pi/3) is very close to 0.5, but not exactly 0.5
abs(cos(pi/3) - 0.5) =   1.11022302e-16

Back to the top

Using arrays in conditional statements

We can also use conditional statements in arrays. In this case, we have to come up with a single truth value for the logical array, and as a result, we must be very careful about how we use logical arrays in conditional statements. For example, consider the following code fragment :

x = -1 + 2*rand(1,5);     % 1x5 array of numbers in [-1,1]
if (x < 0)
    x = -10;
else
    x = 10;
end;
disp(x)
    10

You might think that this sets negative entries in x to -10 and positive entries to 10. But in fact, all it does is set the array x to the scalar value 10. Why? The first statement x < 0 will only be true if all entries of x are negative. Since we probably have a mix of both positive and negative entries, the code will set x to the scalar value 10.

Back to the top

Lab exercises

  1. Plot the following discontinuous function over the interval [-5,5]. Be sure to include any end point conditions.

    $ f(x) = \left\{ \begin{array}{rcc} 3x+4 & \mbox{if} & x \le -1 \\ -x + 7 & \mbox{if} & -1 < x \le 2 \\ 2x - 4 & \mbox{if} & x > 2 \\ 0 & \mbox{otherwise} & \\ \end{array}\right. $

Back to the top

Get the code

Do you want to try the above code fragments on your own? Download the Matlab script that produces this page here. (lab_14.m)

Powered by MathJax

Published with MATLAB® 8.3