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开发者_JAVA技巧 it.
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 1
s).
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 0
s and 1
s.
Crude short form:
>> bincomb = @(x,y) sum([x&y;x&~y;~x&y;~(x|y)]');
>> bincomb(A,B)
ans =
2 0 1 3
精彩评论