2017-05-30 76 views
0

我一直堅持下面的問題幾天,並會感謝任何幫助。我有兩個不同的矩陣,A和B.我有一個開始的x和y位置(xpos,ypos),並且首先要確定在矩陣中某個範圍內的值是否爲「0」的元素B.如果有這樣的元素,我希望這個元素的x和y位置是新的x和y位置。如果沒有任何元素的值爲「0」,我想從矩陣A中的起始位置的特定範圍內選擇具有最高值的元素。然後位置和該元素成爲新的x和y位置。我有以下代碼:如何使用if-else語句選擇不同矩陣中的元素?

for i=1:5 
    range=5 
    xpos=100 
    ypos=100 
    xstart=xpos-range 
    ystart=ypos-range 

    for gg=1:10; %double the range 
     for hh=1:10; 

      if ystart+gg <= 652 && ystart+gg>0 && xstart+hh <= 653 && xstart+hh> 0 && B(xstart+hh,ystart+gg)== 0; 

       xpos = xstart+hh %this becomes the new xposition 
       ypos = ystart+gg 

      else 

       if ystart+gg <= 652 && ystart+gg >0 && xstart+hh <= 653 && xstart + hh >0 && B(xstart+hh,ystart+gg)~= 0; 

        if ystart+gg <= 652 && ystart +gg>0 && xstart+hh <= 653 && xstart+hh>0 && A(ystart + gg, xstart +hh) >= 0.0; 
         maxtreecover = A(ystart + gg, xstart + hh) 

         xpos = xstart + gg %this becomes the new xpos 
         ypos = ystart + hh %this becomes the new ypos 

        end 
       end 
      end 
     end 
    end 
end 

與此問題是,它不移動到搜索A矩陣之前爲一個「0」(在B矩陣)的範圍內進行搜索的所有元素。我如何修改此代碼以反映我打算做的事情?

回答

0

這是一個避免雙循環的代碼重寫。我認爲所有的if條件都是爲了使索引保持有效(在1和矩陣的大小之間),但是它們不能以當前形式工作,因爲索引在同一行中完成!我也使用minmax條件xposypos解決了這個問題。

此解決方案獲取跨越+/- xposypos範圍的子矩陣。然後它計算2個條件,你描述子矩陣內:

  • 獲取的B的第一個元素是零
  • 得到的是一個

代碼的最大元素的位置的位置評論的詳細信息:

% Create matrices A and B 
n = 100; % Size of matrices 
A = rand(n); 
B = rand(n); 
range = 5;   % "radius" of submatrix 
xpos = 50; ypos = 50; % start point 

% Iterate 
for ii = 1:5 
    % Get submatrices around xpos and ypos, using min and max to ensure valid 
    subx = max(1,xpos-range):min(n,xpos+range); 
    suby = max(1,ypos-range):min(n,ypos+range); 
    A_sub = A(suby, subx); 
    B_sub = B(suby, subx); 
    % Find first 0 in submatrix of B, re-assign xpos/ypos if so 
    [yidx, xidx] = find(B_sub == 0, 1); 
    if ~isempty(xidx) 
     xpos = subx(xidx); 
     ypos = suby(yidx); 
    else 
     % Get max from submatrix of A 
     [~, idx] = max(A_sub(:)); 
     [xidx, yidx] = meshgrid(subx, suby); 
     xpos = xidx(idx); 
     ypos = yidx(idx); 
    end 
end 
+0

謝謝!仍試圖理解這一切,但爲什麼「find(B_sub == 0,1)」有「0,1」?爲什麼「find(B_sub == 0)」不夠? – StephD

+0

沒問題......'B_sub == 0'是我們想要*'find' *的條件,所以解釋'0'!那麼'1'意味着你只對第一場比賽感興趣。所以如果子矩陣有5個零,它只會返回第一個索引。這是因爲我們只能重新分配'xpos'和'ypos'到一個值! – Wolfie

+0

也爲我的懶惰變量命名道歉,我認爲我使用「rows」和「cols」可能使事情混亂。 '〜isempty'行後面還有一個錯字。我更新了我的代碼以獲得更好的清晰度,並且它在測試中似乎按預期工作。任何疑問讓我知道... – Wolfie