我有三个矩阵,分别A
是 2 × 3、2 B
× 5 和Index
3 × 5。
A = [1,3,5;2,4,6];
B = [5,3,3,5,3;6,4,4,6,4];
Index = logical([0,0,0,0,1;0,1,1,0,0;1,0,0,1,0]);
我试图查看 B 中的每个列向量是否A
与索引找到的正确列向量匹配。我的代码如下。
error = 0;
for i = 1:size(B,2)
if A(:,Index(:,i)) ~= B(:,i)
error = error + 1;
end
end
error
在这个循环结束时将是 1,因为最后一列B
应该是 [1;2]。我的问题是非常大(10^6)长度的B
and Index
,这变得非常慢。有什么方法可以避免 for 循环还是我注定要失败?
您可以预先构建索引矩阵A*Index
,然后直接测试两个矩阵:
>> error = sum(max(A*Index ~= B))
error =
1
分解,A*Index
生成索引矩阵:
>> A*Index
ans =
5 3 3 5 1
6 4 4 6 2
然后可以直接与B
:
>> A*Index ~= B
ans =
2×5 logical array
0 0 0 0 1
0 0 0 0 1
有了 1000 万个索引,R2021a Online 在循环中在 ~1 秒和 ~100 秒内运行矢量化版本:
>> B = repmat(B, 1, 1e7);
>> Index = repmat(Index, 1, 1e7);
>> tic
error = sum(max(A*Index ~= B));
toc
Elapsed time is 0.952846 seconds.
>> tic
error = 0
for i = 1:size(B,2)
if A(:,Index(:,i)) ~= B(:,i)
error = error + 1;
end
end
toc
Elapsed time is 98.666943 seconds.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句