1

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.

Jxson99
  • 347
  • 2
  • 16

1 Answers1

3

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 2
    Note that is is typically a BAD IDEA to alter or overload standard functions if you don't absolutely have to. -- So definitely go with something like the above 'manual' implementation if possible. Of course you can implement it in a function if desired, just call it `myTimes` rather than `times`. – Dennis Jaheruddin Oct 26 '16 at 14:24
  • Thanks for the answer. The first one is really creative! – Jxson99 Oct 26 '16 at 14:42
  • 1
    @Mason Glad I could help – Luis Mendo Oct 26 '16 at 14:59