Plotting brownian motion matlab

删除回忆录丶 提交于 2019-12-01 11:23:23

问题


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:

  1. You use size as a variable name. Doing so overrides MATLAB's function size.
  2. The function zeros creates an array initialized by zeros, no need for a loop for that.
  3. Instead of calculating randn for 200 times in a loop, you can do it once, with dxdy = randn(2,numParticles,200) and then simply refer to dxdy(:,:,i) within the loop.
  4. 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 to Part(:,:,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 groupand 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!