How can a plot from an "if" inside of a while loop?
Mostrar comentarios más antiguos
So in this piece of code I'm trying to work out how long it takes for gas particles to go from side of a box to the other, assuming only one can go at a time for each interval and also has an equal chance of going left-to-right as well as right-to-left. I have the code working in such a way that I can get the values in the command window, but it won't graph each value of m and n on the same plot against t. Here's the code just trying to plot (t,m)
N=input('The total number of particles in the system is:'); %The total number of particls in the system
n=N; %The number of particles on left side at start.
m=0; %The number of particls remaining on the right side of the system at start.
t=0;
hold on
while m<N/2
t=t+1; %Time interval
r=rand; %Determines if a particle moves from left to right
if r<n/N %Moves particle left to right
n=n-1;
m=m+1;
elseif r>n/N %Moves particle right to left
n=n+1;
m=m-1;
end
display(t);
display(n);
display(m);
end
hold off
plot(t,m)
Respuesta aceptada
Más respuestas (1)
jgg
el 22 de En. de 2016
Try this:
N=input('The total number of particles in the system is:'); %The total number of particls in the system
n=N; %The number of particles on left side at start.
m=0; %The number of particls remaining on the right side of the system at start.
t=0;
big = 10000;
lim = big;
t_vals = zeros(big,1);
m_vals = zeros(big,1);
hold on
while m<N/2
t=t+1; %Time interval
r=rand; %Determines if a particle moves from left to right
if r<n/N %Moves particle left to right
n=n-1;
m=m+1;
elseif r>n/N %Moves particle right to left
n=n+1;
m=m-1;
end
display(t);
display(n);
display(m);
if t+1 > lim
t_vals = [tvals; zeros(big,1)];
m_vals = [tvals; zeros(big,1)];
lim = length(m_vals);
end
t_vals(t+1) = t;
m_vals(t+1) = m;
end
hold off
ind = find(t_vals == 0,2);
plot(t_vals(1:ind(2)-1),m_vals(1:ind(2)-1))
You can also just change plot to scatter and move it inside your while loop.
Categorías
Más información sobre Programming en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!