您可以使用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