Particles Moving Left Or Right On X-Axis

1 Ansicht (letzte 30 Tage)
Kelly McGuire
Kelly McGuire am 18 Jan. 2019
Bearbeitet: Kelly McGuire am 18 Jan. 2019
I just wrote this code to randomly place particles on the x-axis and then randomly assign a velocity so they go right or left. How could I make this code more efficient, and it doesn't seem to be working properly. Not all of the particles move during the simulation. Also, is there a better way to assign velocities to these particles, and make the code more general so I can easily input more particles? Eventually, I want the particles to be able to collide and reverse directiions every time they collide.
% Ants On A Stick Walking Left Or Right
tic
clc
clear all
axis ([0 40 0 40])
set(gca,'box','off','ycolor','w','YTick',[])
hold on
ants = zeros(5,2);
ants(:,1) = rand(1,5)*40;
x = ants(:,1);
y = ants(:,2);
% Random velocity between -1 and 1, i.e. ants moving with random speeds,
% more realistic
%Vel = -1+2*rand(1,5);
% Random velocity, -1 or 1 only, not zero, i.e. simplest case, ants moving left or right with
% same speed
Vel = randi([-1,1],6);
numberToRemove = 0;
Vel(Vel == numberToRemove) = [];
Vel = Vel(1:5);
Vel = Vel';
%plot(x,y,'r.','MarkerSize',30)
% for i = 1:size(ants)
%
for i = 0:0.5:20
AssignVel = ants(:,1).*Vel(:,1);
if AssignVel(1,1) < 0
x(1,1) = x(1,1) - 1;
elseif AssignVel(1,1) > 0
x(1,1) = x(1,1) + 1;
if AssignVel(2,1) < 0
x(2,1) = x(2,1) - 1;
elseif AssignVel(2,1) > 0
x(2,1) = x(2,1) + 1;
if AssignVel(3,1) < 0
x(3,1) = x(3,1) - 1;
elseif AssignVel(3,1) > 0
x(3,1) = x(3,1) + 1;
if AssignVel(4,1) < 0
x(4,1) = x(4,1) - 1;
elseif AssignVel(4,1) > 0
x(4,1) = x(4,1) + 1;
if AssignVel(5,1) < 0
x(5,1) = x(5,1) - 1;
elseif AssignVel(5,1) > 0
x(5,1) = x(5,1) + 1;
end
end
end
end
end
plot(x,y,'r.','MarkerSize',30)
pause(0.5); % change (0.1) to larger values to have a slower animation
cla % Clears previous particle marker from axis
end
%
% end
toc

Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by