1

作業中のコードの一部をベクトル化しようとしていますが、一見同等のforループでは発生しない奇妙な結果が得られます。2つのバージョンが異なる結果を得る理由を誰かが理解できますか?

また、誰かが最初のforループをベクトル化して、各セルのバイナリロケーションマトリックスを生成する方法についてのポインターを持っている場合は、それが適切です。

助けてくれてありがとう

フォーマットされたコード

プレーンコード:

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
4

1 に答える 1

1

コードが同等であるとは思わない: 「順次」バージョンは 2 次元空間 (スライス内) で距離を見つけるため、x = bwdist(locations(:,:,1)(3,3) に最も近い非ゼロ要素が (1,1) である場合、 x(3,3) = sqrt(4+4) = 2.8284、つまり。(1,1) と (3,3) の間の距離。

一方、「ベクトル化されたバージョン」では、距離は 3 次元空間にあり、x = bwdist(locations(:,:,1:2)(3,3,1) に最も近い非ゼロ要素が (1,1,1) ではなく (1,2,1) である場合、 ) なので、x(3,3,1) = sqrt(4+1+1) = 2.4495 です。

于 2012-04-16T01:30:53.047 に答える