Create two matrices using the following code:
A = [0, 1, 0; 1, 0, 1]; B = [1, 1, 0; 0, 0, 1];
A = 0 1 0 1 0 1
B = 1 1 0 0 0 1
C = xor(A,B) performs an exclusive OR of the input matrices
% XOR of matrices A and B R = xor(A,B);
R = 1 0 0 1 0 0
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.
A logical XOR operation returns
true if only one operand is
true, otherwise returns
false (Table 1).
|A||B||A XOR B|
Note: By convention, zero is considered
false and nonzero numbers are considered
I recommend the following books to learn more on logical operations in MATLAB:
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.
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.
Consult the help documentation of the functions
sum. Calculate how many elements in an arbitrary matrix
X are divisible by 2 or 3 (but not by both).
A possible solution could be:
divisibleBy2 = mod(X,2) == 0; divisibleBy3 = mod(X,3) == 0; xorResult = xor(divisibleBy2,divisibleBy3); count = sum(xorResult(:));
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.