Search code examples
matlabxor

Shorthand for an operation involving matrices, using xor


I have 2 matrices

A = [a b; c d];
B = [e f; g h];

where a,b,c,d,e,f,g,h are either 0 or 1.

I want to do

[(a*e) xor (b*g) (a*f) xor (b*h);
 (c*e) xor (d*g) (c*f) xor (d*h)];

Is there any MATLAB command for this operation?


Solution

  • Here is a solution using matrix multiplication:

    result = A*B ==1;
    

    Explanation:

    Your operation is the same as matrix multiplication except that in matrix multiplication we use sum operation instead of xor .Here is the matrix multiplication:

    [(a*e) + (b*g) (a*f) + (b*h);
     (c*e) + (d*g) (c*f) + (d*h)];
    

    With xor we want to see if two operands are different and if we sum two binary numbers the possible outputs are [0 1 2]= [0+0 1+0 1+1] so we can see that only two operands are different if their sum is 1 so we compute the matrix multiplication and check if it equals 1.

    And here is a solution using pre-computed linear indexes:

    result = A([1 1;2 2]) & B([1 3;1 3]) ~= A([3 3;4 4]) & B([2 4;2 4]);