2015-10-03 17 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