How to vectorize random walk simulation in matlab

I am rewriting a monte carlo simulation model in Matlab with a focus on readability. The model includes many particles (represented as (x, y, z)) after randomly wandering around a small set of states with some probabilities of completion. The information related to the output is the number of particles that end in a given state.

Simulation requires a sufficient number of particles, which trigger it for each particle individually, is expensive. Vectorization seems to be a way to get performance from Matlab, but is there any idiomatic way to create a vectorized version of this simulation in Matlab?

I hit my head against a wall to accomplish this - I even tried to create an nStates x nParticles matrix representing each combination of particle states, but this approach quickly gets out of hand (readability) as the particles bounce off of the state independently of each other. Should I just bite the bullet and switch to a language more suitable for this?

+3
source share
1 answer

Just write the code as usual. Almost all Matlab functions can accept and return vectorized input. For example, to simulate the Buryat movement 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

, , , "dot times"

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

, , .

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);

..

+3

Source: https://habr.com/ru/post/1766313/


All Articles