在我的代码中,我有一个缓慢的部分,可以在下面的简短示例中总结这个想法:
A = randi(10,5); %Random 5×5 matrix containing integers ranging from 0 to 10
B = rand(10,1); %Random 10×1 vector containing values ranging from 0 to 1
C = B(A); %New 5×5 matrix consisting of elements from B, indexed using A
在我的情况下,矩阵A的大小为1000×1000,B是500×1的向量,C也是1000×1000。鉴于第3行是for循环,其中A是常量而B每次迭代都更新,我该如何进一步提高速度性能?根据配置文件查看器,75%的代码执行是在这一行。正如预期的那样,对于此操作使用for循环要慢得多(对于1000×1000矩阵,使用10x):
AA = A(:); %Convert matrix to vector
for k=1:length(AA) %Loop through this vector and use it as index
D(k) = B(AA(k));
end
E = reshape(D,5,5); %Reshape vector to matrix of 5x5
有什么想法来优化这个?
编辑:用于衡量绩效的脚本:
N = 1500;
A = randi(500,N);
AA = A(:);
D = zeros(N,N);
B = rand(500,1);
f1 = @() VectorIndex(A,B);
timeit(f1,1)
f2 = @() LoopIndex(AA,B,N);
timeit(f2,1)
function C = VectorIndex(A,B)
C = B(A);
end
function D = LoopIndex(AA,B,N)
D = zeros(N,N);
for k=1:length(AA)
D(k) = B(AA(k));
end
D = reshape(D,N,N);
end