我想减少我的代码中的循环量以加速计算。我遇到了一部分代码,我正在完成一个循环,我看不到解决方案。用于循环替换的Matlab
我有一个矩阵x
y
各种粒子的坐标。 例如,产生作为rand(2,5)
0.8715 0.0363 0.0657 0.6289 0.3279
0.0272 0.4380 0.9794 0.6563 0.4755
我想在(5,5,2)
矩阵与每个粒子之间的载体。 这将是x
长度为(:,:,1)
和y长度为(:,:,2)
的矩阵。
我想减少我的代码中的循环量以加速计算。我遇到了一部分代码,我正在完成一个循环,我看不到解决方案。用于循环替换的Matlab
我有一个矩阵x
y
各种粒子的坐标。 例如,产生作为rand(2,5)
0.8715 0.0363 0.0657 0.6289 0.3279
0.0272 0.4380 0.9794 0.6563 0.4755
我想在(5,5,2)
矩阵与每个粒子之间的载体。 这将是x
长度为(:,:,1)
和y长度为(:,:,2)
的矩阵。
为此,您可以使用bsxfun
,但您还需要使用permute
“3D转置”坐标矩阵。 permute
变成coordinates
成5×1×2和1×5×2阵列,分别为:
coordinates = rand(2,5);
%# subtract all coordinate pairs from one another
vectorArray = bsxfun(@minus,permute(coordinates,[2,3,1]),permute(coordinates,[3 2 1]));
size(vectorArray)
ans =
5 5 2
注意,vectorArray是反对称的,所以你可能想看看如果遇到空间问题,则进入pdist
。
下面是一个使用REPMAT创建linear index入坐标矩阵和CAT创建3-d矩阵结果基于索引的解决方案:
>> xy = [0.8715 0.0363 0.0657 0.6289 0.3279; ... %# Your coordinates
0.0272 0.4380 0.9794 0.6563 0.4755];
>> N = size(xy, 2);
>> index = repmat(1:2:2*N, N, 1); %# A matrix of linear indices into xy
>> result = cat(3, xy(index)-xy(index.'), ... %.'# X differences
xy(index+1)-xy(index.'+1)) %.'# Y differences
result(:,:,1) =
0 -0.8352 -0.8058 -0.2426 -0.5436
0.8352 0 0.0294 0.5926 0.2916
0.8058 -0.0294 0 0.5632 0.2622
0.2426 -0.5926 -0.5632 0 -0.3010
0.5436 -0.2916 -0.2622 0.3010 0
result(:,:,2) =
0 0.4108 0.9522 0.6291 0.4483
-0.4108 0 0.5414 0.2183 0.0375
-0.9522 -0.5414 0 -0.3231 -0.5039
-0.6291 -0.2183 0.3231 0 -0.1808
-0.4483 -0.0375 0.5039 0.1808 0