From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: random walk & random number
Date: Wed, 6 Nov 2013 21:11:06 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 28
Message-ID: <l5eb9a$s59$>
References: <l5dauc$5p$> <l5e0ii$d19$> <l5e9di$77$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1383772266 28841 (6 Nov 2013 21:11:06 GMT)
NNTP-Posting-Date: Wed, 6 Nov 2013 21:11:06 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: comp.soft-sys.matlab:804907

"nawal " <> wrote in message <l5e9di$77$>...

> "Roger Stafford" wrote in message <l5e0ii$d19$>...
> >  ..... To accomplish this it would be wise to enclose your code, including the necessary initializations, in an outer for-loop to do the appropriate repetition and collect the rg2 values in a vector, rather than manually repeating your code.

> What do you mean by outer for loop? I've just started learning matlab so I'm still not familiar with it.
- - - - - - - - - -
  By "outer loop" I mean doing something like: for k = 1:10000 in front of the code you wrote and at its end storing the rg2 you have calculated in a vector RG2 having 10000 (or whatever number of runs you select) elements with the line:

 RG2(k) = rg2;

After that of course you need an 'end' to terminate this outer loop.  Also you need to delete the plot command.

  I should point out that the code for producing a vector rg2 for a large number of runs can easily be vectorized rather than using nested for-loops, and besides having fewer lines of code it might execute faster.

 N = 10000; % Choose the desired number of hundred-step runs
 n = 100; % The number of steps in each run
 r = ceil(4*rand(n,N)); % Compute random integers from 1 to 4
 px = [1;0;-1;0]; py = [0;1;0;-1]; % Use these to translate them to 1, 0, and -1
 X = cumsum([zeros(1,N);reshape(px(r),n,N)],1); % Compute the random walks
 Y = cumsum([zeros(1,N);reshape(py(r),n,N)],1);
 rg2 = mean(X.^2,1)+mean(Y.^2,1)-mean(X,1).^2-mean(Y,1).^2; % Get variances

The quantity rg2 will be an N-element row vector containing your "distance" variance for each of the N runs.  You can use this to compute a histogram for it.

  Note: Of course you do not get to see the individual random walk plots this way.  For that you would have to set N equal to 1 in the above and do plot(X,Y) to see a typical walk.

Roger Stafford