Matlab 如何为同一矩阵/数组的不同索引上的操作向量化嵌套for循环?
我一直在尝试在Matlab中对for循环进行矢量化,因为它会使整个程序陷入瓶颈,但我不知道在循环中对单个矩阵的不同行或列进行迭代时如何进行矢量化。代码如下:Matlab 如何为同一矩阵/数组的不同索引上的操作向量化嵌套for循环?,matlab,matrix,vectorization,Matlab,Matrix,Vectorization,我一直在尝试在Matlab中对for循环进行矢量化,因为它会使整个程序陷入瓶颈,但我不知道在循环中对单个矩阵的不同行或列进行迭代时如何进行矢量化。代码如下: // X is an n*k matrix, W is n*n // W(i,j) stores the norm of the vector resulting from subtracting // the j-th line of X from its i-th line. for i = 1:n for j = 1:n
// X is an n*k matrix, W is n*n
// W(i,j) stores the norm of the vector resulting from subtracting
// the j-th line of X from its i-th line.
for i = 1:n
for j = 1:n
W(i,j) = norm(X(i,:) - X(j,:))
end
end
编辑:
我选择了Luis Mendo的答案,因为它对我来说是最方便的,而且更接近我算法背后的数学概念,但这三个答案都是正确的,我建议使用最方便的答案,这取决于您使用的Matlab工具箱或您想要的编码方式
我还注意到所有答案的共同点是使用不同的格式,例如:使用存储索引的数组,重塑当前数组,使用一个维度。。。
因此,如果您有类似的问题,我认为这是正确的探索方法。使用组合:
% sample data
X = randi(9,5,4);
n = size(X,1);
% row index combinations
combIdx = combvec(1:n,1:n);
% difference between row combinations
D = X(combIdx(1,:),:)-X(combIdx(2,:),:);
% norm of each row
W = diag(sqrt(D*D'));
% reshape
W = reshape(W,n,[]);
使用组合法:
% sample data
X = randi(9,5,4);
n = size(X,1);
% row index combinations
combIdx = combvec(1:n,1:n);
% difference between row combinations
D = X(combIdx(1,:),:)-X(combIdx(2,:),:);
% norm of each row
W = diag(sqrt(D*D'));
% reshape
W = reshape(W,n,[]);
这是另一个可能对大型矩阵更有效的解决方案 对于Matlab>=R2016,您可以简单地使用
W = sqrt(sum(abs(reshape(X,n,1,k) - reshape(X,1,n,k)).^2,3))
(如果数组是实值数组,也可以跳过abs)。对于早期版本的Matlab,您需要添加一些repmat magic,即:
W = sqrt(sum(abs(repmat(reshape(X,n,1,k),[1,n,1]) - repmat(reshape(X,1,n,k),[n,1,1])).^2,3));
附言:R2017b可能会使它更加方便,至少提到一个名为
vecnorm
的函数,它可以取代有点难看的sqrt(sum(abs(.^2))
东西。但是文档还没有准备好,所以我不知道它到底能做什么。“这是另一种可能对大型矩阵更有效的解决方案
对于Matlab>=R2016,您可以简单地使用
W = sqrt(sum(abs(reshape(X,n,1,k) - reshape(X,1,n,k)).^2,3))
(如果你的数组是实数,你也可以跳过abs)。对于早期版本的Matlab,你需要添加一些repmat魔法,即:
W = sqrt(sum(abs(repmat(reshape(X,n,1,k),[1,n,1]) - repmat(reshape(X,1,n,k),[n,1,1])).^2,3));
附言:R2017b可能会使它更方便,至少提到一个名为vecnorm
的函数,它可以取代有点难看的sqrt(sum(abs(.^2))
东西。但是文档还没有准备好,所以我不知道它到底会做什么。”- 如果您有统计工具箱,请使用:
- 没有工具箱:好旧:
- 如果您有统计工具箱,请使用:
- 没有工具箱:好旧: