2015-02-10 80 views
1

一行我清楚地记得一位专家码上ij一些条件检查,如果该评估为真,他们将标志着,在矩阵。在下面显示的行上的东西。他们做到了这一点!有人可以告诉如何?在Matlab中编码下面几行的最有效方法是什么?向量化嵌套的for循环在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检查。如果上面编辑的东西很复杂会怎么样?

+0

下一次,你问一个问题请提供*所有*的详细信息,以避免根据提供的答案编辑问题。谢谢! – 2015-02-10 21:19:20

回答

2

您可以使用logical indexing这里采取的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 

所以,教训 -

  1. 更换3*i+4*j>=2bsxfun(@plus,3*ii',4*jj)>=26*i-j<=6bsxfun(@plus,6*ii',-1*jj)<=。为什么bsxfun?那么,你有两个嵌套循环,其中ij作为迭代器,所以你需要形成一个二维掩码,每个迭代器都有一个维度。

  2. 通过加入这两个较早的条件来形成完整的条件语句匹配逻辑数组,如loopy代码&&中所做的那样。不过,您只需将其更改为&即可。

  3. 让逻辑索引照顾故事的其余部分!

希望这必须引导您使用条件语句更复杂的代码。


旁注:您还可以使用ndgridmeshgrid这里形成二维条件/二进制数组,这可能是更直观 -

%// 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 
+0

感谢您的解释。 – giffy 2015-02-10 21:38:37

+0

@giffy绝对是我的荣幸!添加了一个可能对你有趣的旁注! – Divakar 2015-02-10 21:59:31

+0

如果我有一个圆条件,'I * I + J *Ĵ<= 2',将这项工作'条件1 = bsxfun(@加,II * II”,JJ * JJ。)<= 2; '? – giffy 2015-02-11 20:18:03