Matlab code to analyze data on a grid -
i have point set (x,y) coordinates , corresponding weights in matrix 1st, 2nd , 3rd columns x, y, , weight respectively. want divide point set grid cells, , count number of points in each grid , total weight of each grid.
i tried small example below, did not work. here tried divide data set 2x2 small grid , tried count number of points , sum of weights. further, have big data set, can not extend approach further when need different step sizes grid.
can please me develop easier approach?
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]; i=1:6 if data(i,1)<=2 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 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 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'
if x
, y
not yet rounded arbitrary units, first:
x = round((x - min(x))/edgelength+1);
this makes sure obtain grid edgelength
sized squares, indicated non-zero integers. same y
.
then can use either sparse
or accumarray
total weight. sparse
faster, less wide applicable:
gridweight = sparse(x,y,weight);
if want average weights, add 1 each entry , divide matrix:
numentries = sparse(x,y,1); meanweights = gridweight./numentries;
accumarray
can both of these operations in 1 go:
gridweight = accumarray([x y],weight); meanweights = accumarray([x y], weight,[],@mean); %//add ,[], 'issparse' sparse matrix
note sparse
sub-functionality of accumarary
setting accumarray=([i,j],val,[],@sum,[],'issparse')
. function sparse
can handle @sum
, it's sole fill-value 0
, whilst accumarray
other functions , values can used.
Comments
Post a Comment