2015-10-03 19 views
0

我有一個點(x,y)座標及其在矩陣a中的相應權重,其中第1列,第2列和第3列分別是x,y和權重。我想將這個點集合劃分成網格單元格,並計算每個網格中的點數和每個網格的總重量。用於分析網格上的數據的Matlab代碼

我試過下面的小例子,但它沒有奏效。在這裏,我試圖將這個數據集分成一個2×2的小網格,並試圖計算點數和它們的權重總和。此外,我有大數據集,所以當我需要不同的網格步長時,我無法進一步擴展這種方法。

有人可以幫我開發一個更簡單的方法嗎?

function dataTree 
count=zeros(9,1); 
avg=zeros(9,1); 
data=[1 3 100; 2 1 120; 3 5 110; 4 2 100; 5 3 150; 6 2 100]; 

for i=1:6 
    if data(i,1)<=2 
     for j=1:6 
      if data(j,2)<=2 
       count(1) = count(1) + 1; 
       avg(1) = avg(1) + data(j,3); 
      elseif data(j,2)<=4 
        count(2) = count(2) + 1; 
        avg(2) = avg(2) + data(j,3); 
      elseif data(j,2)<=6 
        count(3) = count(3) + 1; 
        avg(3) = avg(3) + data(j,3); 
      end 
     end 
    elseif data(i,1)<=4 
     for j=1:6 
      if data(j,2)<=2 
       count(4) = count(4) + 1; 
       avg(4) = avg(4) + data(j,3); 
      elseif data(j,2)<=4 
        count(5) = count(5) + 1; 
        avg(5) = avg(5) + data(j,3); 
      elseif data(j,2)<=6 
        count(6) = count(6) + 1; 
        avg(6) = avg(6) + data(j,3); 
      end 
     end 
    elseif data(i,1)<=6 
     for j=1:6 
      if data(j,2)<=2 
       count(7) = count(7) + 1; 
       avg(7) = avg(7) + data(j,3); 
      elseif data(j,2)<=4 
        count(8) = count(8) + 1; 
        avg(8) = avg(8) + data(j,3); 
      elseif data(j,2)<=6 
        count(9) = count(9) + 1; 
        avg(9) = avg(9) + data(j,3); 
      end 
     end 

    end 
end 
count' 
avg' 
+1

看看這裏http://stackoverflow.com/questions/32902553/matlab-matrix-range-assignment – Wauzl

回答

1

如果您xy尚未四捨五入到一些任意單位,這樣做第一:

x = round((x - min(x))/edgelength+1); 

這可以確保您獲得網格edgelength大小的正方形,它是由非表示零整數。對y做同樣的事情。

然後您可以使用sparseaccumarray來獲得總重量。 sparse速度較快,但廣不太適用:

gridWeight = sparse(x,y,weight); 

,如果你想獲得的平均體重,加1爲每個條目,然後除以該矩陣:

NumEntries = sparse(x,y,1); 
MeanWeights = gridWeight./NumEntries; 

accumarray都可以做這些操作一氣呵成:

gridWeight = accumarray([x y],weight); 
MeanWeights = accumarray([x y], weight,[],@mean); %//add ,[], 'issparse' for sparse matrix 

注意sparseaccumarary通過設置子功能。唯一的功能sparse可以處理的是@sum,它的唯一填充值是0,而accumarray可以使用其他函數和值。

+1

感謝您的詳細解答。它真的幫助我。 – Frey