[英]How can I use an if-else statement to select elements in different matrices?
我已經在以下問題上停留了幾天,希望能對您有所幫助。 我有2個不同的矩陣A和B。我有x和y的起始位置(xpos,ypos),首先要確定矩陣中是否存在某個范圍內的值為“ 0”的元素B.如果存在此類元素,我希望此元素的x和y位置成為新的x和y位置。 如果沒有任何值為“ 0”的元素,我想從矩陣A的起始位置中選擇一個在特定范圍內具有最高值的元素。然后該位置和該元素變為新的x和y位置。 我有以下代碼:
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矩陣之前,它不會在B矩陣中搜索“ 0”范圍內的所有元素。 如何修改此代碼以反映我的意圖?
這是對代碼的重新編寫,避免了雙循環。 我假設您所有的if
條件都使索引保持有效(介於1和矩陣的大小之間),但是它們無法以當前形式工作,因為無論如何索引都是在同一行完成的! 我也使用xpos
和ypos
min
和max
條件解決了這個問題。
此解決方案獲得的子矩陣跨越xpos
和ypos
范圍的+/-范圍。 然后,它將評估您在該子矩陣中描述的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.