matlab循环矢量化 嵌套,在Matlab中对for循环进行矢量化,得到不同结果的看似等效的代码...

在本文中,作者遇到了一个编程问题,即在处理代码时,两个看似相同的for循环产生了不同的结果。作者创建了一个矩阵,为每个单元格生成一个二进制位置矩阵,但在使用`bwdist`函数计算距离时,矢量化版本的循环给出了错误的距离值。代码示例展示了这两个版本的循环,并在最后进行了比较。问题在于如何修正矢量化版本以得到正确的距离值。
摘要由CSDN通过智能技术生成

我正在尝试引导我正在处理的一段代码,但是我收到了奇怪的结果,这些结果不会发生在看起来相同的for-loop中。任何人都可以看到为什么这两个版本获得不同的结果?

此外,如果任何人有任何指示我如何能够引导第一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值