x = rand(numParticles,1) * LR;
y = rand(numParticles,1) * BR;
theta = 2*pi*rand(numParticles,1);
boxes = [0.8e-7 0.0e-7 0.4e-7 0.4e-7;
0.8e-7 0.6e-7 0.4e-7 0.4e-7];
x_traj = zeros(numParticles, numSteps);
y_traj = zeros(numParticles, numSteps);
outX = (x_new<0) | (x_new>LR);
outY = (y_new<0) | (y_new>BR);
x_new(outX) = x(outX) + vx(outX)*dt;
y_new(outY) = y(outY) + vy(outY)*dt;
bx = boxes(b,1); by = boxes(b,2); bw = boxes(b,3); bh = boxes(b,4);
inBoxX = (x_new > bx) & (x_new < bx+bw);
inBoxY = (y_new > by) & (y_new < by+bh);
crossedLeft = (x <= bx) & (x_new > bx) & inBoxY;
crossedRight = (x >= bx+bw)& (x_new < bx+bw)& inBoxY;
crossedBottom = (y <= by) & (y_new > by) & inBoxX;
crossedTop = (y >= by+bh)& (y_new < by+bh)& inBoxX;
vx(crossedLeft | crossedRight) = -vx(crossedLeft | crossedRight);
vy(crossedBottom | crossedTop) = -vy(crossedBottom | crossedTop);
x_new(crossedLeft | crossedRight) = x(crossedLeft | crossedRight) + vx(crossedLeft | crossedRight)*dt;
y_new(crossedBottom | crossedTop) = y(crossedBottom | crossedTop) + vy(crossedBottom | crossedTop)*dt;
plot(x_traj(i,:), y_traj(i,:));
rectangle('Position', boxes(b,:), 'FaceColor', [1 1 1], 'EdgeColor', 'k', 'LineWidth', 2);