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, with dxdy = randn(2,numParticles,200)
and then simply refer to dxdy(:,:,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 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 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?