2012-04-16 17 views
1

我試圖vectorise我正在處理的一段代碼,但我得到奇怪的結果不發生在看似等價的for循環。任何人都可以看到爲什麼這兩個版本獲得不同的結果?另外,如果任何人有任何關於如何能夠引導第一個循環的指針,併爲每個單元格生成一個二進制位置矩陣,那將是甜蜜的。在Matlab中矢量化for循環,得到不同的結果,看似等效的代碼

非常感謝您的幫助

Formatted code

明碼:

function create_distances() 
x=3; % Dimensions of grid 
y=3; 
num_cells=x*y; % Num of cells in grid 

% In following code a matrix is generated for each cell, in which that cell 
% is set to 1 and all others zero. 
locations=zeros(x,y,num_cells); % Initialise blank array to store each location on grid 
for current_index=1:num_cells; 
    temp=locations(:,:,current_index); 
    temp([current_index])=1;% Set a single cell to 1 to represent which cell is the active one for each of the cells 
    locations(:,:,current_index)=temp; % Store back to that location matrix 
end 

%%For loop version which correctly creates the distances 
distances_from_position1=zeros(x,y,num_cells); 
for current_location1=1:num_cells 
    distances_from_position1(:,:,current_location1)=bwdist(locations(:,:,current_location1)); 
end 

% Vectorised version of same code which gives incorrect distance values 
current_location2=1:num_cells; 
distances_from_position2=zeros(x,y,num_cells); 
distances_from_position2(:,:,current_location2)=bwdist(locations(:,:,current_location2)); 

%Gives correct results 
correct_values=distances_from_position1 

%incorrect_values=distances_from_position2; 

if eq(distances_from_position1,distances_from_position2)==1 
    disp('Same results') 
else 
    disp('Two methods give different results') %This message shown each time 
end 

回答

1

我不認爲代碼是等價的:在 「連續」 版本發現2-d的距離空間(片內),所以如果x = bwdist(locations(:,:,1)最接近於(3,3)的非零元素是(1,1),並且我們有x(3,3)= sqrt(4 + 4)= 2.8284,即。 (1,1)和(3,3)之間的距離。另一方面,使用「矢量化版本」的距離是在3-D空間,並且如果x = bwdist(locations(:,:,1:2)最接近的非零元素(3,3,1)不是(1,1,1),但是( 1,2,1),那麼x(3,3,1)= sqrt(4 + 1 + 1)= 2.4495。

+0

好的,謝謝你的輸入。 這似乎對應於[在這裏(鏈接)](http://www.mathworks.co.uk/products/matlab/demos.html?file=/products/demos/shipping/matlab/nddemo.html #7): 「在平面或2D矩陣上運行的函數(如EIG)不接受多維數組作爲參數。要將這些函數應用於多維數組的不同平面,請使用索引或FOR循環。 由於bwdist在2D矩陣上運行,我認爲這就是爲什麼它不起作用。我唯一的選擇是在循環中計算距離值嗎? 再次感謝 – 2012-04-16 12:53:19

+0

實際上,bwdist DOES可以在3D矩陣上運行,並且*根據文檔正確工作 - 也就是計算3D空間中的距離並將2D矩陣當作它們處理堆疊在彼此的頂部。但是,因爲這不是你想要的,所以我認爲你必須去循環... – laxxy 2012-04-16 22:06:51