gpt4 book ai didi

matlab - 在 Matlab 中优化循环

转载 作者:行者123 更新时间:2023-12-04 01:03:46 26 4
gpt4 key购买 nike

我有三个矩阵,A 是 2 x 3,B 是 2 x 5,Index 是 3 x 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]。我的问题是 BIndex 的长度非常大 (10^6),这变得非常慢。有什么方法可以避免 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.

关于matlab - 在 Matlab 中优化循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67224393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com