Azzera filtri
Azzera filtri

how can i count number of particles in each grid box after running this code ??

3 visualizzazioni (ultimi 30 giorni)
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;

Risposta accettata

Geoff Hayes
Geoff Hayes il 29 Giu 2015
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.
  5 Commenti
sneha kriplani
sneha kriplani il 7 Lug 2015
@geoff when i am trying this one then matlab is howing error that no strings to take as input ?? Can you please tell me what correction to make,, m new in matlab so need ur help,, Thanks
Geoff Hayes
Geoff Hayes il 8 Lug 2015
Sneha - you will have to post the code that you are using as well as the full error message as it isn't clear to me which line may be throwing the error.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Tables in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by