我想減少我的代碼中的循環量以加速計算。我遇到了一部分代碼,我正在完成一個循環,我看不到解決方案。用於循環替換的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