MATLAB: Count how many times an if statement executes

countfor loopif statementsimulation

I'm plotting the trajectory of a moving particle in a 2D box which bounces off the walls as you'd expect.
For the next part of the problem I have to calculate the impulse on ONE of the walls throughout the simulation, meaning I need to know how many times the particle hits that wall.
Below is the relevant section of my code, which looks good to me, but the count keeps coming up as 0 even though I can see the particle rebounding off all 4 walls.
n = 100; %number of time-steps
min_wall = -5; max_wall = 5; %position of container walls
x = zeros(1,n); y = zeros(1,n); %particle positions
v_x = zeros(1,n); v_y = zeros(1,n); %particle velocity
v0_x = 1; v0_y = 1.5; %initial velocity components
v_x(1) = v0_x; v_y(1) = v0_y; %set initial velocity
for i=2:n
count = 0;
%new position = old position + velocity * time
x(i) = x(i-1) + v_x(i-1);
y(i) = y(i-1) + v_y(i-1);
%conditions to model elastic collisions b/w particle and walls
if x(i) < min_wall
count = count + 1; %add to collision count
x(i) = 2 * min_wall - x(i); %reflect particle position across wall
v_x(i) = -v_x(i-1); %switch sign of velocity component normal to wall
v_y(i) = v_y(i-1);
%...
end
Can anyone see what's wrong/missing?

Best Answer

You want to initialize count to zero before your for loop not inside your for loop.
Related Question