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

2 views (last 30 days)
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?

Accepted Answer

Star Strider
Star Strider on 26 Mar 2016
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.
  4 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Graphics Performance in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!