您可以像这样完全矢量化:
n = numel(xl);
[X, Y] = meshgrid(1:n,1:n);
Ix = X(:)
Iy = Y(:)
reshape(sqrt((xl(Ix)-xl(Iy)).^2+(yl(Ix)-yl(Iy)).^2+(zl(Ix)-zl(Iy)).^2), n, n);
如果您查看Ix
and Iy
(尝试像 3x3 数据集一样),它们使每个矩阵的线性索引的每种组合成为可能。现在您可以一次完成每个减法!
然而,混合 shoelzer 和 Jost 的建议会给你带来几乎相同的性能提升:
n = 50;
xl = rand(n,1);
yl = rand(n,1);
zl = rand(n,1);
tic
for t = 1:100
distanceMatrix = zeros(n); %// Preallocation
for i=1:n
for j=min(i+1,n):n %// Taking advantge of symmetry
distanceMatrix(i,j) = sqrt((xl(i)-xl(j))^2+(yl(i)-yl(j))^2+(zl(i)-zl(j))^2);
end
end
d1 = distanceMatrix + distanceMatrix'; %'
end
toc
%// Vectorized solution that creates linear indices using meshgrid
tic
for t = 1:100
[X, Y] = meshgrid(1:n,1:n);
Ix = X(:);
Iy = Y(:);
d2 = reshape(sqrt((xl(Ix)-xl(Iy)).^2+(yl(Ix)-yl(Iy)).^2+(zl(Ix)-zl(Iy)).^2), n, n);
end
toc
回报:
Elapsed time is 0.023332 seconds.
Elapsed time is 0.024454 seconds.
但是,如果我更改n
为,500
那么我会得到
Elapsed time is 1.227956 seconds.
Elapsed time is 2.030925 seconds.
这只是表明,在将循环记为慢之前,您应该始终在 Matlab 中对解决方案进行基准测试!在这种情况下,根据解决方案的规模,循环可能会明显更快。