Back to tutorial index

Using logical operators and conditional statements


Topics in this lab

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

Warning : Suppose we want to check whether x = -3 is between -4 and 0. Mathematically, we might write $$-4 \le x \le 0.$$ But a direct translation of this expression into Matlab can have unexpected results. For example,

x = -3;
-4 <= x <= 0
ans =

     0

Matlab interprets this by evaluating from left to right. Writing the same expression using parenthesis, it is perhaps clearer how Matlab is evaluating this expression.

(-4 <= x) <= 0
ans =

     0

The expression in the parenthesis evaluates to true, which Matlab stores are the integer value 1.

m = -4 <= x
m =

     1

The next conditional statement checks to see if m is less than 0, and of course it is not.

m <= 0
ans =

     0

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.4817    0.4753    0.8938    0.0202    0.5838   -0.0957    0.6984

x > 0
ans =

     1     1     1     1     1     0     1

x < 0
ans =

     0     0     0     0     0     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.4817    0.4753    0.8938    0.0202    0.5838    0.6984

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

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

   -0.0957

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
x =

   10.0000   10.0000   10.0000   10.0000   10.0000   -0.0957   10.0000

html To set all the values less than 10 to -10, we can em>negate</em the mask array class="var">m</span.

x(~m) = -10
x =

    10    10    10    10    10   -10    10

We can shorten the above by simply writing

x = -1 + 2*rand(1,7)
x =

   -0.2191    0.4768    0.9529    0.0466   -0.1402   -0.5857   -0.3532

y = 10*(x > 0) + -10*(x < 0)
y =

   -10    10    10    10   -10   -10   -10

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)
  % b is not equal to 0
  c = a/b;
else
  fprintf('Cannot divide by 0\n');
end;
Cannot divide by 0

As a more complex example, we determine whether a quadratic polynomial has 0, 1 or two real roots, and whether the parabola opens up or down. We start by generating random integer coefficients in the interval $[-5,5]$.

% -----------------------------------------------------
% Find the roots of a quadratic function.
% -----------------------------------------------------
coeffs = round(-5 + 10*rand(1,3));
a = coeffs(1);
b = coeffs(2);
c = coeffs(3);

fprintf('The coefficients of the polynomial are : ');
fprintf('a = %d,  b = %d,  c = %d\n',a,b,c);
fprintf('\n');

% First, determine if the function is really quadratic
if a == 0
    is_quadratic = false;
    fprintf('The parabola is degenerate (a line).\n');
else
    is_quadratic = true;
    if a > 0
        fprintf('The parabola opens up.\n');
    else
        fprintf('The parabolic opens down.\n');
    end
end
fprintf('\n');

if ~is_quadratic
    % The polynomial is not quadratic
    if c ~= 0
        r = -b/c;
    else
        r = b;
    end
    nroots = 1;
else
    % Compute the discriminant
    D = b*b - 4*a*c;

    if D < 0
        nroots = 0;    % two imaginary roots
        r = [];
    elseif D == 0
        nroots = 1;    % one real (multiple) root
        r = -b/(2*a);
    else
        nroots = 2;    % two real roots
        r(1) = (-b - sqrt(D))/(2*a);
        r(2) = (-b + sqrt(D))/(2*a);
    end
end

if (nroots == 0)
    fprintf('There are no real roots.\n');
elseif nroots == 1
    fprintf('The real root is : \n');
    fprintf('r = %12.4f\n',r);
else
    fprintf('The real roots are : \n');
    for i = 1:nroots,
        fprintf('r(%d) = %12.4f\n',i,r(i));
    end
end
The coefficients of the polynomial are : a = -4,  b = -1,  c = -2

The parabolic opens down.

There are no real roots.

In the above, we had conditional statements checking to see whether a real number is equal to 0. In general, it is not a good idea to check for exact equality when compare the values of two real numbers. Consider the following example.

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('abs(cos(pi/3) - 0.5) = %16.8e\n',abs(x-0.5));
cos(pi/3) is not exactly 0.5!
abs(cos(pi/3) - 0.5) =   1.11022302e-16

In finite precision arithmetic, we cannot compute the exact value of the function cos(x).

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]
disp(x)
   -0.3158    0.6342    0.0634    0.0422    0.5486

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

Using the Matlab 'find' function

Sometimes, you may want to know the indices of the entries in an array that meet some criteria. For example, suppose we wanted to know where the first non-zero number in an array occurs. The Matlab find function will return for us an array of indices at which some logically array is set to true.

x = -1 + 2*rand(1,5)   % random numbers in [-1,1]
x =

   -0.7595    0.2509   -0.3067   -0.3308    0.1492

idx = find(x > 0)       % Find all entries > 0
idx =

     2     5

if (~isempty(idx))
    fprintf('The first positive entry is in location %d\n',idx(1));
end
The first positive entry is in location 2

The array idx contains the indices of the positive entries. If no entries are found meeting the criteria, then find returns an empty array.

Back to the top

Lab exercises

In this lab, you will practice using conditional statements.
  1. Use a mask to find all the entries in the vector x that are between -0.5 and 0.5.
  2. x = -1 + 2*rand(10,1).
    
  3. Use the Matlab find function to find the index of the first three entries in the array x
    x = -10 + 20*rand(100,1);
    
    that are between -5 and 5.
  4. Estimate the value of $\pi$ by generating $N$ random points $(x,y)$ in the square $[-1,1] \times [-1,1]$ and counting how many of these points are in the unit circle of radius 1 centered at the origin. How large should $N$ be to get three digits of accuracy?
  5. Construct the Heaviside Function $H(x)$ defined as $$ H(x) = \left\{\begin{array}{rcl} 0 & \mbox{if} & x \le 0 \\ 1 & \mbox{if} & x > 0\\ \end{array}\right. $$ Plot the function $H(x-3)$ over the interal $[-5,5]$.
  6. Plot the following discontinuous function over the interval [-5,5]. Be sure to include any end point conditions. Use only an array 'mask' to select points to include in each piece. $$ f(x) = \left\{\begin{array}{rcl} 3x + 7 & \mbox{if} & x \le -1 \\ -x + 7 & \mbox{if} & -1 < x \le 2 \\ 2x-4 & \mbox{if} & x > 2\\ \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_13.m)

Powered by MathJax

Published with MATLAB® 8.3