# Repeating while loop to form matrix

5 views (last 30 days)

Show older comments

I am simulating a random walk, I have a while loop that creates an array of the distance the particle is from the starting point for each iteration. I would like to then take this while loop and repeat it to simulate multiple particles at once, and then create a matrix that combined all the previous arrays. I am trying to repeat the while loop with a for loop. RIght now it only gives me back the matrix but with one row (when in this example it should have 3) and when I get multiple rows its all of the same array. ANy help would be appreciated

i = 10; %iteration time step

t = 0; %current time

p = 0; % current position

d = 0; %distance from orgin

A = zeros(1,i);%array of distances

B = [1:i];

p = 3 %number of particles

multiple_distance=[] %matrix of distances

for ii = 3

while t < i

r=rand;

if r<0.5

l=1;

else

l=-1;

end

x = x + l;

d = abs(0-x);

t = t+1;

A(t)=x;

end

A

multiple_distance = [multiple_distance ; A]

end

##### 0 Comments

### Answers (1)

Bob Thompson
on 4 Jun 2021

Edited: Bob Thompson
on 4 Jun 2021

You've only indexed one value (ii = 3 means it will only ever be 3), which is why you're only getting one line completed.

for ii = 1:3 % Loops through all values from 1 to 3

while t < i

r=rand;

if r<0.5

l=1;

else

l=-1;

end

x = x + l;

d = abs(0-x);

t = t+1;

A(t)=x;

end

A

multiple_distance = [multiple_distance ; A]

end

I'm pretty sure this can be done without loops at all, but I'm going to have to spend a bit more time figuring out what the code is doing before I can give you an answer on that.

##### 4 Comments

Bob Thompson
on 4 Jun 2021

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!