用于分析网格上数据的 Matlab 代码

Matlab code to analyze data on a grid

我在矩阵 a 中有一个具有 (x,y) 坐标及其相应权重的点集,其中第一、第二和第三列分别是 x、y 和权重。我想把这个点集分成网格单元,统计每个网格中的点数和每个网格的总权重。

我尝试了下面的小例子,但是没有用。在这里,我尝试将这个数据集划分为一个 2x2 的小网格,并尝试计算点数及其权重之和。此外,我有大数据集,所以当我需要不同的网格步长时,我不能进一步扩展这种方法。

有人可以帮我开发一个更简单的方法吗?

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'

如果您的 xy 尚未舍入到某些任意单位,请先舍入:

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

这确保您获得具有 edgelength 大小正方形的网格,由非零整数表示。对 y.

做同样的事情

然后您可以使用 sparse or accumarray 来计算总重量。 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

请注意,通过设置 accumarray=([i,j],val,[],@sum,[],'issparse')sparseaccumarary 的子功能。 sparse 可以处理的唯一函数是 @sum,它唯一的填充值是 0,而对于 accumarray 可以使用其他函数和值。