Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vectorize a random walk simulation in MATLAB

I am rewriting a Monte Carlo simulation model in MATLAB with an emphasis on readability. The model involves many particles, represented as (x,y,z), following a random walk over a small set of states with certain termination probabilities. The information relevant for output is the number of particles that terminate in a given state.

The simulation requires enough particles that running it for each particle individually is cost prohibitive. Vectorization seems to be the way to get performance out of MATLAB, but is there any idiomatic way of creating a vectorized version of this simulation in MATLAB?

I'm beating my head against the wall to accomplish this - I've even tried creating a (nStates x nParticles) matrix representing each particle-state combination, but this approach quickly spirals out of control in terms of readability since particles bounce from state to state independently of one another. Should I just bite the bullet and switch to a language more suitable for this?

like image 430
turtlesoupy Avatar asked Sep 24 '10 02:09

turtlesoupy


People also ask

How do I generate a random walk in Matlab?

N = 100; % Length of the x-axis, also known as the length of the random walks. M = 400; % The amount of random walks. for n = 1:N % Looping all values of N into x_t(n). A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.

What is random walk simulation?

Random walk is a simulation where a succession of random steps is used to represent an apparently random event.


1 Answers

Just write the code as you normally would. Almost all matlab functions can accept and return vectorized input. For instance, to simulate a brownian motion of N particles in 1 dimension

position = zeros([N 1]); %start at origin
sigma = sqrt(D * dt); %D is diffusion coefficient, dt is time step
for j = 1:numSteps
    position = position + sigma*randn(size(position));
end

if you wanted to have a different sigma for each position, you would make sigma a vector the same size as position and use "dot times" notation to indicate element by element operation

position = position + sigma.*randn(size(position));

if the scattering was an arbitrary function of position and some random element, you would just have to write a vectorized function, e.g.

function newstep = step(position)
%diffusion in a overdamped harmonic potential
newstep = -dt*k*position + D*randn(size(position));

for j = 1:numsteps; position = position + step(position);

and so on

like image 167
Marc Avatar answered Nov 16 '22 01:11

Marc