我正在尝试对我正在处理的一段代码进行矢量化,但是我得到了一些奇怪的结果,这些结果在看似等效的 for 循环中不会发生。谁能明白为什么这两个版本会得到不同的结果?
此外,如果有人对我如何矢量化第一个 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