MATLAB: How can i count number of particles in each grid box after running this code ?

matlab cvst

xyRange=[1,5]; %// Starting xy range of particles
P=3; %// Number of particles generated each day
vx=0.6; vy=0.4; %// x and y velocity
X=[]; Y=[]; %// Vectors start out empty
for day=1:10
%// Generate 3 particles and add to end of vectors X and Y
X=[X;randi(xyRange,P,1)];
Y=[Y;randi(xyRange,P,1)];
%// Move all the particles
X=X+vx;
Y=Y+vy;
end
plot(X,Y,'kd');
grid on ;
axis([1,50,1,50]);
j = floor(X/5)+1;
k = floor(Y/5);
box = k*10+j;

Best Answer

sneha - if you have the Statistics Toolbox you may be able to use hist3 to create a bivariate histogram that will count the number of hits per grid/square.
If you don't (like me!) you could just create a 10x10 array and use it to store all of the particle counts (hits) for each square. You would then iterate over each (x,y) pair and see which square it would fall into. Try the following
numSquares = 10;
squareStepSz = 5;
squareHitCount = zeros(numSquares, numSquares);
for k=1:size(X,1)
x = X(k);
y = Y(k);
ySqrIdx = min(numSquares - ceil(y/squareStepSz) + 1, numSquares);
xSqrIdx = min(ceil(x/squareStepSz), numSquares);
squareHitCount(ySqrIdx, xSqrIdx) = squareHitCount(ySqrIdx, xSqrIdx) + 1;
end
The above code assumes that the grid is divided into numSquares (10) rows and columns, with the "step size" of each square being squareStepSz (5), and that all coordinates are positive (x>0, y>0 for each (x,y) pair).
We pre-size the hit count matrix and then start intreating over each pair. Note how we divide each coordinate by the step size, round up to the nearest integer (using ceil) and then for the case of the y coordinate, we manipulate it in such a way so that we choose the correct element of our hit array to populate. (We do this because we want the matrix to populate bottom up like your plot.)
The result is then
squareHitCount =
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
2 6 3 0 0 0 0 0 0 0
5 14 0 0 0 0 0 0 0 0
which seems to correspond well with your code that produces the above plot.