说A
和B
是length(A) = length(B)
的2个向量。
A
和B
的所有元素都是0
或1
。如何在1行中计算两个向量具有值1
的位置数?
答案 0 :(得分:3)
只需添加到解决方案列表中,您也可以使用点积,它将为您提供答案:
C=A'*B; %'# here I've assumed A & B are both column vectors
到目前为止,这也是所发布解决方案的 最快 。
时间测试
A=round(rand(1e5,1));
B=round(rand(1e5,1));
点积
tic;for i=1:1e4;A'*B;end;toc %'SO formatting
Elapsed time is 0.621839 seconds.
NNZ
tic;for i=1:1e4;nnz(A&B);end;toc
Elapsed time is 14.572747 seconds.
总和(BITAND())
tic;for i=1:1e4;sum(bitand(A,B));end;toc
Elapsed time is 64.111025 seconds.
答案 1 :(得分:1)
许多解决方案之一,使用nnz
代替sum
来查找非零元素的数量:
nnz(A&B)
答案 2 :(得分:0)
这应该这样做:
sum(bitand(A, B))