MATLAB: Hello I have a problem with the coding, with drawnow in the opinion? But it could be something else

circlecollisiondrawnowfor loopif statementissueloopphysicsrandom number generator

Hello, so basically I want to code beads which move left and write independently to each other unless if they collide. I haven't written the collision algorithm so far, but right now i've gotten a problem with my plotting: When running my code, instead of having 2 balls simply move along the screen (left and right), i get the balls leaving a trail behind them while moving (as seen in attached pic.)
Part of my code is this (which i believe causes the problem since the other is just sorting out):
for t = 0:500
for n=1:(nMolecules-1) %MMCollision check
m=n+1;
end
for n = 1:nMolecules
% Wall collision check (Only 1st and last molecules)
if (Molecule(1,n)<= 0.5*Molecule(3,n))
Molecule(4,n) = -Molecule(4,n); %Elastic Collision
elseif (Molecule(1,n)>= Right-0.5*Molecule(3,n))
Molecule(4,n) = -Molecule(4,n); %Elastic Collision
end
Molecule(1,n) = Molecule(1,n) + Molecule(4,n);
end
hold on
for n=1:nMolecules
xlim([Left Right]);
ylim([Down Up]);
if (Molecule(2,n)==4) %Drawing different balls based on rng
h = plot(Molecule(1,n),Molecule(5,n),'o','Color','black','MarkerFaceColor','red','MarkerSize',100*Molecule(3,n));
else
h = plot(Molecule(1,n),Molecule(5,n),'o','Color','black','MarkerFaceColor','blue','MarkerSize',100*Molecule(3,n));
end
end
hold off
drawnow
end
Basically my code randomly attributes a size to a ball and its "properties" like mass and radius data (not in provided code). The provided image shows both being of the same size and yes, there's supposed to be only 2 balls on the screen, instead of 10+
Anybody can help me?

Best Answer

We’re missing some code. Even if I define ‘nMolecules’, ‘Molecule’ remains undefined.
I can’t run your code, but from my experience, if you don’t want the ‘trail’ effect, eliminate the hold calls.
I wrote this for a — not yet Accepted but hope but never fades — Answer a week ago.
It’s not your intended application, but perhaps you can glean some ideas from it, since I did not use hold, and put the axis limits just after the plot (in my code, surf) call:
[X,Y] = meshgrid(linspace(-5, 5, 50));
fcn = @(x,y,k) k*x.^2 + y.^2;
v = [1:-0.05:-1; -1:0.05:1];
for k1 = 1:2
for k2 = v(k1,:)
surfc(X, Y, fcn(X,Y,k2))
axis([-5 5 -5 5 -30 50])
drawnow
pause(0.1)
end
end
Run it! It’s fun to watch! I goes from an attractor basin to a saddle-point and back. I put the pause call in to make it appear relatively smooth. Tweak that as necessary.