Search code examples
arraysmatlabmultiplicationelementwise-operations

How to set 0 x 0 = 1 in a element-wise array multiplication? MATLAB


I have two column vector A and B of same length n.

In both vectors, there are only 3 possible values for their elements: -1, 0 and 1.

When I multiply A by B element-wise, I hope to get the expect results for 1x1, 1x(-1) and (-1)x(-1).

However, here, when 0 is a term in the multiplication, I'd like to get the following results:

0x0 = 1

0x1 = -1

0x(-1) = -1

Element-wise multiplication is easy in MATLAB:

times(A,B) or A.*B

I'd like know how to set up a predefined result for an operation, say, 0x0 =1. Knowing this one, I'll be able to deal with the others.


Solution

  • You could override the times function (see here), but it's easier to do the operation manually as follows: multiply normally and then replace the 0 results (which correspond to either A or B equal to 0) with the modified value (1 if A and B are equal and -1 otherwise):

    A = [1 -1 0 1 1 0 1];
    B = [1 1 -1 -1 0 0 1];
    result = A.*B;
    ind = result==0;
    result(ind) = 2*(A(ind)==B(ind))-1;
    

    You can also do it as follows in one line, but less efficient:

    result = A.*B + ~(A&B).*(2*(A==B)-1);
    

    This gives

    A =
         1    -1     0     1     1     0     1
    B =
         1     1    -1    -1     0     0     1
    result =
         1    -1    -1    -1    -1     1     1