Tutorial

Logical XOR in MATLAB

The function xor performs a logical eXclusive-OR in MATLAB.

Preparation

Create two matrices using the following code:

A = [0, 1, 0; 1, 0, 1];
B = [1, 1, 0; 0, 0, 1];

Syntax

C = xor(A,B) performs an exclusive OR of the input matrices A and B.

% XOR of matrices A and B
R = xor(A,B);

If A and B are nonscalar matrices, they must have the same size. If one input is scalar and the other is nonscalar, the scalar input is treated as if it were the same size as the other input.

To learn how logical XOR works, see Table 1.

Truth table

A logical XOR operation returns true if only one operand is true, otherwise returns false (Table 1).

Table 1. Truth table of the logical XOR operation.
A B A XOR B
True True False
True False True
False True True
False False False

Note: By convention, zero is considered false and nonzero numbers are considered true.

Further reading

I recommend the following books to learn more on logical operations in MATLAB:

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. Chapters 4 and 5 explain selection statements and loops, two areas that extensively make use of logical operations.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The eighth chapter covers logical operations and selection statements.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

doc xor;

Exercise

Consult the help documentation of the functions mod and sum. Calculate how many elements in an arbitrary matrix X are divisible by 2 or 3 (but not by both).

Source code

I hope you have learned how to perform a logical XOR in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.