【问题标题】:Vectorising a for-loop in Matlab, getting different result for seemingly equivalent code在 Matlab 中对 for 循环进行矢量化,为看似等效的代码获得不同的结果
【发布时间】:2012-04-16 00:30:36
【问题描述】:

我正在尝试对我正在处理的一段代码进行矢量化,但我得到了在看似等效的 for 循环中不会发生的奇怪结果。谁能看出为什么这两个版本会得到不同的结果?

另外,如果有人对我如何向量化第一个 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

【问题讨论】:

    标签: matlab vector vectorization


    【解决方案1】:

    我不认为代码是等效的:“顺序”版本在二维空间(切片内)中找到距离,所以如果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。

    【讨论】:

    • 好的,感谢您的意见。这似乎与here (link) 所说的相符:“像 EIG 这样在平面或二维矩阵上运行的函数不接受多维数组作为参数。要将这些函数应用于多维数组的不同平面,请使用索引或 FOR 循环。 "由于 bwdist 在二维矩阵上运行,我认为这就是它不起作用的原因。我唯一的选择是循环计算距离值吗?再次感谢
    • 实际上,bwdist 确实在 3-D 矩阵上运行,并且 按照文档正常工作 - 即计算 3-D 空间中的距离,并处理二维矩阵就好像它们堆叠在一起一样。但是,由于这不是您想要的,所以我认为您必须使用循环...
    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多