在matlab中的一行中向量化嵌套的for循环
vectorising nested for-loops in one line in matlab
我清楚地记得专家代码检查 i
、j
上的某些条件,如果评估为真,他们会在矩阵中标记它。如下所示的线条上的东西。他们在一行中做到了这一点!有人能告诉我怎么做吗?在 Matlab 中编写以下代码行的最有效方法是什么?
for i=1:nrows
for j=1:ncolumns
if (3*i+4*j>=2 && 6*i-j<=6)
obstacle(i,j)=1;
end
end
end
编辑:
我在 i,j
上设置了非常简单的条件检查。如果事情像上面编辑的那样复杂怎么办?
您可以使用 logical indexing
here and take help of bsxfun
来处理像这样的复杂条件语句 -
%// Define vectors instead of the scalar iterators used in original code
ii=1:nrows
jj=1:ncolumns
%// Look for logical masks to satisfy all partial conditional statements
condition1 = bsxfun(@plus,3*ii',4*jj)>=2 %//'
condition2 = bsxfun(@plus,6*ii',-1*jj)<=6 %//'
%// Form the complete conditional statement matching logical array
all_conditions = condition1 & condition2
%// Use logical indexing to set them to the prescribed scalar
obstacle(all_conditions) = 1
所以,教训 -
将 3*i+4*j>=2
替换为 bsxfun(@plus,3*ii',4*jj)>=2
,将 6*i-j<=6
替换为 bsxfun(@plus,6*ii',-1*jj)<=
。为什么 bsxfun
?好吧,那里有两个嵌套循环,其中 i
和 j
作为迭代器,因此您需要形成一个二维掩码,这两个迭代器各有一个维度。
通过连接这两个较早的条件形成完整的条件语句匹配逻辑数组,就像在带有 &&
的循环代码中所做的那样。不过,您只需要将其更改为 &
。
让逻辑索引处理剩下的事情!
希望这能指导您使用带有条件语句的更复杂的循环代码。
旁注: 你也可以在这里使用 ndgrid
or meshgrid
来形成二维 conditional/binary 数组,这可以更直观 -
%// Form the 2D matrix of iterators
[I,J] = ndgrid(1:nrows,1:ncolumns)
%// Form the 2D conditional array and use logical indexing to set all those
obstacle(3*I+4*I>=2 & 6*I-J<=6) = 1
我清楚地记得专家代码检查 i
、j
上的某些条件,如果评估为真,他们会在矩阵中标记它。如下所示的线条上的东西。他们在一行中做到了这一点!有人能告诉我怎么做吗?在 Matlab 中编写以下代码行的最有效方法是什么?
for i=1:nrows
for j=1:ncolumns
if (3*i+4*j>=2 && 6*i-j<=6)
obstacle(i,j)=1;
end
end
end
编辑:
我在 i,j
上设置了非常简单的条件检查。如果事情像上面编辑的那样复杂怎么办?
您可以使用 logical indexing
here and take help of bsxfun
来处理像这样的复杂条件语句 -
%// Define vectors instead of the scalar iterators used in original code
ii=1:nrows
jj=1:ncolumns
%// Look for logical masks to satisfy all partial conditional statements
condition1 = bsxfun(@plus,3*ii',4*jj)>=2 %//'
condition2 = bsxfun(@plus,6*ii',-1*jj)<=6 %//'
%// Form the complete conditional statement matching logical array
all_conditions = condition1 & condition2
%// Use logical indexing to set them to the prescribed scalar
obstacle(all_conditions) = 1
所以,教训 -
将
3*i+4*j>=2
替换为bsxfun(@plus,3*ii',4*jj)>=2
,将6*i-j<=6
替换为bsxfun(@plus,6*ii',-1*jj)<=
。为什么bsxfun
?好吧,那里有两个嵌套循环,其中i
和j
作为迭代器,因此您需要形成一个二维掩码,这两个迭代器各有一个维度。通过连接这两个较早的条件形成完整的条件语句匹配逻辑数组,就像在带有
&&
的循环代码中所做的那样。不过,您只需要将其更改为&
。让逻辑索引处理剩下的事情!
希望这能指导您使用带有条件语句的更复杂的循环代码。
旁注: 你也可以在这里使用 ndgrid
or meshgrid
来形成二维 conditional/binary 数组,这可以更直观 -
%// Form the 2D matrix of iterators
[I,J] = ndgrid(1:nrows,1:ncolumns)
%// Form the 2D conditional array and use logical indexing to set all those
obstacle(3*I+4*I>=2 & 6*I-J<=6) = 1