问题
First of all, I just want to say that I'm not that used to using matlab, but I need for an assignment, I'm supposed to create a "brownian movement". My code is currently looking like this:
clf
hold on
prompt = 'Ge ett input';
size = input(prompt) ;
numParticles = input('Ange antal partiklar');
axis([-size size -size size]);
Part = [];
color = 'brkgmyco';
for i = drange(1:numParticles)
Part = [Part [0;0]];
end
for i = drange(1:200)
dxdy = randn(2,numParticles);
k = Part
Part = Part + dxdy;
My concern is how to print, I would even want like a small delay on every print, so you really can see what's happening for the assignment, is this possible to achieve from the code I've written for now or should anything be changed? Thanks in advance!
回答1:
Here are some basic problems with your code, regardless of what you are trying to do:
- You use
size
as a variable name. Doing so overrides MATLAB's function size. - The function zeros creates an array initialized by zeros, no need for a loop for that.
- Instead of calculating
randn
for 200 times in a loop, you can do it once, withdxdy = randn(2,numParticles,200)
and then simply refer todxdy(:,:,i)
within the loop. - The same holds for summation. Instead of summing within a loop to get the cumulative sum, use cumsum like
Part = cumsum(randn(2,numParticles,200),3);
and then refer toPart(:,:,i)
, within the loop.
Now to your task. You said you want to know how to print, but I believe you want to plot because you use some commands like axis
, clf
and hold
, that refer to graphic objects. However, you never really do plot anything.
The basic and general function for plotting in 2D is plot, but there are many other more specific functions. One of them is scatter
, and it has a sister function gscatter, that takes triples of x
, y
and group
and plot each (x(k),y(k))
colored by their group(k)
.
This code plots the particles on an axes, and animate their movement:
prompt = 'Ge ett input';
scope = input(prompt) ;
numParticles = input('Ange antal partiklar');
N = 500;
Part = cumsum(randn(2,numParticles,N)*scope/100,3);
h = gscatter(Part(1,:,1),Part(2,:,1),1:numParticles);
axis([-scope scope -scope scope]);
legend off
for k = 2:N
for p = 1:numParticles
h(p).XData = Part(1,p,k);
h(p).YData = Part(2,p,k);
end
drawnow
end
Is this what you look for?
来源:https://stackoverflow.com/questions/39632393/plotting-brownian-motion-matlab