user537670
user537670

Reputation: 821

Binary Operations in MATLAB

I have two vectors A = [1 0 0 0 0 1] and B = [1 0 0 1 0 1]. I want to calculate the number of (1,1) (1,0) (0,1) and (0,0) from the vectors in matlab. Any idea how to go with it.

Upvotes: 0

Views: 3052

Answers (1)

arne.b
arne.b

Reputation: 4330

Did you consider reading a Matlab tutorial? You might have found an answer faster than waiting for it to appear here.

Anyway, the matlab operator for logical AND is &, and the one for logical negation is ~, and both work also on double vectors and matrices (i.e. the default type of which A and B are when defined as in your question; all non-zero values values will be treated like 1s).

Once you have made the required connection, sum(x) will give you the number of ones in x if x is of type logical or a double with only 0s and 1s.

Crude short form:

>> bincomb = @(x,y) sum([x&y;x&~y;~x&y;~(x|y)]');
>> bincomb(A,B)

    ans =

         2     0     1     3

Upvotes: 4

Related Questions