Tra*_*man 5 matlab boolean vector vectorization
我有一个ID号重复偶数次的矢量.我只对每个数字出现的第二次感兴趣.我想创建一个布尔掩码,为每个第二次出现的数字提供一个真/ 1.我已经用循环完成了这个,但实际的向量将包含数百万个元素,因此循环太慢了.我需要一个"矢量化"解决方案.
这是一个示例Vector:
101
102
103
101
104
102
101
103
101
104
Run Code Online (Sandbox Code Playgroud)
这应输出以下掩码:
0 (first occurrence of 101)
0 (first occurrence of 102)
0 (first occurrence of 103)
1 (second occurrence of 101)
0 (first occurrence of 104)
1 (second occurrence of 102)
0 (third occurrence of 101)
1 (second occurrence of 103)
1 (fourth occurrence of 101)
1 (second occurrence of 104)
Run Code Online (Sandbox Code Playgroud)
让我们bsxfun来看看矢量化的解决方案 -
%// Assuming A as the input vector
M = bsxfun(@eq,A(:),unique(A(:).')) %//'
out = any(M - mod(cumsum(M,1).*M,2),2)
Run Code Online (Sandbox Code Playgroud)