如何避免在 Matlab 中嵌套循环以获得更好的 CPU 时间



我应该为较大的 p 值计算这个公式,所以 4 个嵌套循环使我的代码非常慢且不适用。如果有人能帮助我更好地实现 sum 和其他合适的 matlab 命令,我将不胜感激!K(i,j)=sum(sum(a(m)*b(n)*A(i,j,m,n),m=1:p),n=1:p);i,j,m,n ->1:PA 是 4D 矩阵,a,b 是矢量。谢谢。

我可以摆脱 2 个for循环。 也许这个网站上的一个 MATLAB 向导可以做得更好。

p = 3;
A = rand(p, p, p, p)
a = rand(p, 1)
b = rand(p, 1)
% I think your original code does something like this.
K1 = zeros(p, p);
for n = 1: p
    for m = 1: p
        for j = 1: p
            for i = 1: p
                K1(i, j) = K1(i, j) + a(m) * b(n) * A(i, j, m, n);
            end
        end
    end
end
K1
% This gives the same result, with half the loops.
K2 = zeros(p, p);
for n = 1: p
    for m = 1: p
        K2 = K2 + a(m) * b(n) * A(:,:,m,n);
    end
end
K2
% Verify that the two answers are the same.
all(K1(:) == K2(:))

最新更新