2015-02-10 124 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