您可以使用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
所以,教训 -
更换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
作为迭代器,所以你需要形成一个二维掩码,每个迭代器都有一个维度。
通过加入这两个较早的条件来形成完整的条件语句匹配逻辑数组,如loopy代码&&
中所做的那样。不过,您只需将其更改为&
即可。
让逻辑索引照顾故事的其余部分!
希望这必须引导您使用条件语句更复杂的代码。
旁注:您还可以使用ndgrid
或meshgrid
这里形成二维条件/二进制数组,这可能是更直观 -
%// 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
下一次,你问一个问题请提供*所有*的详细信息,以避免根据提供的答案编辑问题。谢谢! – 2015-02-10 21:19:20