MATLAB: How can a plot from an “if” inside of a while loop

while loop

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)

Best Answer

Pre-allocate a large array to load values into during the loop. At the end of the loop, you can plot them all at once. I added tMax to limit the while loop and give an initial size for m and n arrays.
N=input('The total number of particles in the system is:');
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.
tMax = 10000; % Maximum number of periods before exiting loop
mArray = NaN(tMax,1); % Initialize array to store m values
nArray = NaN(tMax,1); % Initialize array to store n values
t=0;
while m<N/2 && t<tMax
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
nArray(t) = n;
mArray(t) = m;
end
mArray = mArray(1:t);
nArray = nArray(1:t);
plot([mArray,nArray]);
legend({'m','n'});
Hope this helps.