Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Matlab 3-d Walk problem

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 19 Nov, 2010 01:16:03

Message: 1 of 18

     Hi everyone. So, I'm currently taking a physics course which happens to involve a computer project; the project is a statistical analysis of a 3-dimensional random walk (each step being the same length and random in x,y,and z orientations). I'm fairly new to Matlab (I originally learned programming a couple years ago in C, but most of that has since been forgotten).

     Anyways, here is a description of what I have so far...

     -To begin the code, I started by creating a unit vector (I used spherical coordinates for the unit because I was able to set r=1, and I then decomposed the vector for its x, y and z components).

The problem...I am able to create my randomly oriented unit vectors, and I am assuming since it is inside of a "for" loop to account for all N steps. Right now, my code returns a list of the vectors that compose each step, I just need to figure out how to add them. Once I get this part, the statistical analysis comes into play, which should then be no problem.

Does anybody have an idea of how to do this, or a way around it?

Subject: Matlab 3-d Walk problem

From: Darren Rowland

Date: 19 Nov, 2010 01:50:05

Message: 2 of 18

Something like this perhaps, where the positions visited are recorded, rather than the steps.

position = zeros(3,N+1);
for k = 2:N+1
    step = 2*rand(3,1)-1; % Create a random step in (x,y,z)
    step = step/norm(step); % Normalise to unit length
    position(:,k) = position(:,k-1) + step; % Add new step to last position
end

Hth
Darren

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 19 Nov, 2010 02:13:04

Message: 3 of 18

Okay, so I understand conceptually what you mean, but I get lost in the code. Right now, here is what I have:


%This program creates a random unit vector in 3D. It then sums over many of
%these unit vetors in order to create a total displacement, R. Once it has
%found R, it then creates many more displacement vectors and finds the average displacement, R.
clear all


    for n = 1:1000
    %this repeats for 1000 random walks
        
        for N=1:100
           %accounts for 100 steps
            
            r=1;
            phi=rand(1)*pi;
            theta=rand(1)*2*pi;
            %creates one 3d unit vector randomly oriented
            
            Rx= r*sin(phi)*cos(theta);
            Ry= r*sin(phi)*sin(theta);
            Rz= r*cos(phi);
            %breaks down vector into x,y,z components

            R=[Rx;Ry;Rz];
            %returns random unit vector for each of 100 steps
            
        end
        
    end
    end


     I'm not sure exactly how to incorporate what you said. My attempt to try and incorporate a Rxnew=Rxlast+Rx, but I couldn't get the labelling right (I think this is similar to what you said about keeping track of present position. Then, my next thought was that maybe I could somehow return the result vectors from the loop to create a matrix and then sum over all x's, y's and z's to find net displacement, but I can't figure out a way to do that w/the loop present. Either way, if you could help enlighten/walk me through this a little, it would be greatly appreciated. Thank you.

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 19 Nov, 2010 02:34:05

Message: 4 of 18

Nevermind, what you posted makes perfect sense and is a lot more efficient than what I had. Thank you.

Subject: Matlab 3-d Walk problem

From: Darren Rowland

Date: 19 Nov, 2010 06:03:03

Message: 5 of 18

No problem. Here is an alternative method which forms the random steps, then uses cumsum to get the resultant positions

N = 10;
steps = 2*rand(3,N)-1;
steps = steps./repmat(sqrt(sum(steps.^2,1)),3,1); % Normalize to unit length
position = cumsum([zeros(3,1) steps],2); % Obtain set of positions,
% assuming starting at the origin

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 19 Nov, 2010 19:09:04

Message: 6 of 18

That method seems better. For this project, I'm supposed to run through data sets for the number of steps being 100, 1000, 10000 and 100000 so it was taking a while to run. MY question now is, would there be a way to just return the final value instead of the value after each iteration? That would be much easier to work with when I have to run my data analysis.

Subject: Matlab 3-d Walk problem

From: Sean de

Date: 19 Nov, 2010 19:23:03

Message: 7 of 18

"Justin Twardowski" <jtwardow@email.arizona.edu> wrote in message <ic6i0g$o8e$1@fred.mathworks.com>...
> That method seems better. For this project, I'm supposed to run through data sets for the number of steps being 100, 1000, 10000 and 100000 so it was taking a while to run. MY question now is, would there be a way to just return the final value instead of the value after each iteration? That would be much easier to work with when I have to run my data analysis.

So instead of using cumsum, which updates at each step, just use sum to get the end result?

Subject: Matlab 3-d Walk problem

From: Roger Stafford

Date: 19 Nov, 2010 23:00:08

Message: 8 of 18

"Darren Rowland" <darrenjremovethisrowland@hotmail.com> wrote in message <ic53un$jf2$1@fred.mathworks.com>...
> .......
> steps = 2*rand(3,N)-1;
> ........
- - - - - - - - - - -
  If the direction of each step is to be uniformly distributed in three-dimensional orientation, it would be better to use the randn function:

 steps = randn(3,N);
 position = cumsum(bsxfun(@rdivide,steps,sqrt(sum(steps.^2,1))),2);

  It can easily be shown that this method with randn results in a statistically uniform distribution sphere-wise, whereas 2*rand(3,N)-1 gives a degree of preference to the eight corner directions and therefore depends on how the xyz axes are oriented. To see this, imagine a cube with a tangential sphere inside and an orthogonal projection of the cube's volume onto the surface of this sphere. The quantity 2*rand(3,N)-1 fills the inside of a 2x2x2 cube uniformly. Therefore the eight corner directions would receive a somewhat higher density on the spherical surface (by a factor of 3*sqrt(3) in fact) than the directions orthogonal to the six faces.

Roger Stafford

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 21 Nov, 2010 01:41:03

Message: 9 of 18

"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in message <ic6vho$3rn$1@fred.mathworks.com>...
> "Darren Rowland" <darrenjremovethisrowland@hotmail.com> wrote in message <ic53un$jf2$1@fred.mathworks.com>...
> > .......
> > steps = 2*rand(3,N)-1;
> > ........
> - - - - - - - - - - -
> If the direction of each step is to be uniformly distributed in three-dimensional orientation, it would be better to use the randn function:
>
> steps = randn(3,N);
> position = cumsum(bsxfun(@rdivide,steps,sqrt(sum(steps.^2,1))),2);
>


Hi Roger,

     Thank you for your contribution; seeing as this problem is a statistical analysis, it's reassuring to know I now have the proper distribution to work with. Anyways, I've been looking over the second line of code you've posted, and am struggling to understand and modify it to suit my needs. Would you be able to walk me though the process going on there? I understand that the first line is generating an array of random values, and I'm guessing that the normalization is taken into consideration in the second line? Also, I've been struggling to write this code in a way that returns me what I think I need for my analysis, and that is an array of the displacements that I can work with by adding, etc with the elements to find displacement and other quantities.

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 21 Nov, 2010 01:55:04

Message: 10 of 18

I thought I should specify how I need my data to be returned. The other main quantity being examined is the mean displacement squared; that's why I'm assuming an array of the vector steps would be nice to work with. Thanks to everyone, again.

Subject: Matlab 3-d Walk problem

From: Roger Stafford

Date: 21 Nov, 2010 04:59:05

Message: 11 of 18

"Justin Twardowski" <jtwardow@email.arizona.edu> wrote in message <ic9u5o$bkb$1@fred.mathworks.com>...
"Justin Twardowski" <jtwardow@email.arizona.edu> wrote in message <ic9tbf$jqe$1@fred.mathworks.com>...
>> Thank you for your contribution; seeing as this problem is a statistical analysis, it's reassuring to know I now have the proper distribution to work with. Anyways, I've been looking over the second line of code you've posted, and am struggling to understand and modify it to suit my needs. Would you be able to walk me though the process going on there? I understand that the first line is generating an array of random values, and I'm guessing that the normalization is taken into consideration in the second line? Also, I've been struggling to write this code in a way that returns me what I think I need for my analysis, and that is an array of the displacements that I can work with by adding, etc with the elements to find displacement and other quantities.
> I thought I should specify how I need my data to be returned. The other main quantity being examined is the mean displacement squared; that's why I'm assuming an array of the vector steps would be nice to work with. Thanks to everyone, again.
- - - - - - - - -
  That code is easier to discuss if I replace it with the equivalent 'repmat' version instead of using 'bsxfun' and break it up into individual temporary arrays.

 steps = randn(3,N);
 t1 = sum(steps.^2,1);
 t2 = sqrt(t1);
 t3 = repmat(t2,3,1);
 steps = steps./t3;
 position = cumsum(steps);

  The first step creates a three-dimensional multivariate Gaussian distribution of points with mean zero and standard deviation one for each coordinate in a 3 by N array. It is easy to show that the probability density is dependent only on the distance from the origin and not the rotational angles, since randn values are statistically independent.

  The second step computes the sum of the squares of each column resulting in a 1 by N row vector. The third step takes the square root of these, obtaining the distance from the origin of each of the points, and the vector remains 1 by N. The fourth step makes duplicates of this distance row vector, resulting in a 3 by N array in which all three rows are the same.

  The fifth step does normalization. It amounts to a projection of each point onto the unit sphere about the origin. Each coordinate of a point is divided by the point's distance from the center, so the adjusted point is now perforce a unit distance from the center and therefore lies on the unit sphere. The previous 'repmat' operation was needed so the the "./" operation would have operands of the same size to work with. Using bsxfun instead of repmat is a way of creating a smarter division process that carries out the same operation. At this point each column of 'steps' is an individual change of position of magnitude one taken in a random direction.

  The final sixth step computes the cumulative vector sum of these steps starting with the first step, then the sum of the first two steps, then the sum of the first three steps, and so forth until N steps have been taken. The variable 'position' is therefore also a 3 by N array with each column representing the resulting position in 3D starting at the origin, after N steps. The last column gives the final position.

  I am rather puzzled by what you mean by "mean displacement squared". Each step above has a displacement magnitude of one and the mean of that squared would of course also be one. Perhaps you refer to the mean of the squares of each of the coordinate increments, or perhaps the mean of the square of the final distance from the start point over many experiments? Whatever your desired computation it seems very likely you can obtain it from some simple operation on either 'steps' or 'position'.

Roger Stafford

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 21 Nov, 2010 16:38:03

Message: 12 of 18

Hi Roger,

     Thanks again. This project is due tomorrow and today is the day I hopefully finish this up. Thank you for your explanation; it helped me understand that better (I am still unfamiliar with certain commands, their uses and syntax). Anyways, I'm going to try applying what you said and see if I could get it to work.
     In terms of the mean squared displacement, which I failed to explain. In my simulation, I run walks of 100, 1000, 10000, and 100000 steps, and repeat those each 1000 times to find my average displacement after N steps, n walks. The mean squared displacement that I'm supposed to find and evaluate is with regards to the 1000 repeated trials per the given numbers of steps (so this is repeated 4 times). In this case, the distance is just 1 so it seems trivial, but I'm still supposed to "show it" via the code.

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 21 Nov, 2010 18:42:03

Message: 13 of 18

Hi, so I've been trying to get a start with the code Roger posted, but am having trouble summing over the displacement positions over 1000 walks to get an average displacement. Here is the bare structure of what I have; I just can't figure out the right expression to add up the displacements in my second innermost loop.

P.S. this is probably an elementary question, it's just been a long time since I've last programmed so this is fairly rusty; thanks for bearing with me




clear al
l
    for k=2:5
        for n=1000
            for N=10^k

            steps = randn(3,N);
            %creates random array for use as vectors

            t1 = sum(steps.^2,1);
            t2 = sqrt(t1);
            t3 = repmat(t2,3,1);
            steps = steps./t3;
            %normalizes

            R = sum(steps,2)
            %sums over steps to return total displacement vector for one walk
            
            Rsq=norm(R)^2
            %returns total displacement squared for one walk

 
            end
            %this is the space I feel my expression should be to add the net displacements from the innermost loop (which represents position after one walk)

        end
    end

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 21 Nov, 2010 19:54:04

Message: 14 of 18

bump

Subject: Matlab 3-d Walk problem

From: Justin Twardowski

Date: 21 Nov, 2010 22:37:03

Message: 15 of 18

Anyone? I feel like my information is being outputted in the wrong fashion for me to be able to work with and sum over the 1000 repeated walks.

Subject: Matlab 3-d Walk problem

From: Darren Rowland

Date: 22 Nov, 2010 06:06:03

Message: 16 of 18

There are a few ways you might do it but here is one which - I think - does what you want.

function avgDispK = randWalk3D
numTrials = 1000;
avgDispK = zeros(4,1);
for k = 2:5
    N = 10^k;
    totalDisplacement = 0;
    for n = 1:numTrials
        
        steps = randn(3,N);
        %creates random array for use as vectors
        
        t1 = sum(steps.^2,1);
        t2 = sqrt(t1);
        t3 = repmat(t2,3,1);
        steps = steps./t3;
        %normalizes
        
        R = sum(steps,2);
        %sums over steps to return total displacement vector for one walk
        
        Rsq = norm(R)^2;
        %returns total displacement squared for one walk
        
        totalDisplacement = totalDisplacement + Rsq;
    end
    avgDispK(k-1) = totalDisplacement/numTrials;
end

Subject: Matlab 3-d Walk problem

From: Vivekananda Bal

Date: 6 Nov, 2013 13:39:08

Message: 17 of 18

Hi everybody, I am presently working on lattice modelling, where we have to move aparticle in 3D randomly along the sides of a cubic lattice. I want to create a random unit vector along the lattice (6 possible ways of moving the particle). I am little bot confused about it. Can you guys please suggest me a suitable way?



"Justin Twardowski" wrote in message <ic4mfg$r55$1@fred.mathworks.com>...
> Okay, so I understand conceptually what you mean, but I get lost in the code. Right now, here is what I have:
>
>
> %This program creates a random unit vector in 3D. It then sums over many of
> %these unit vetors in order to create a total displacement, R. Once it has
> %found R, it then creates many more displacement vectors and finds the average displacement, R.
> clear all
>
>
> for n = 1:1000
> %this repeats for 1000 random walks
>
> for N=1:100
> %accounts for 100 steps
>
> r=1;
> phi=rand(1)*pi;
> theta=rand(1)*2*pi;
> %creates one 3d unit vector randomly oriented
>
> Rx= r*sin(phi)*cos(theta);
> Ry= r*sin(phi)*sin(theta);
> Rz= r*cos(phi);
> %breaks down vector into x,y,z components
>
> R=[Rx;Ry;Rz];
> %returns random unit vector for each of 100 steps
>
> end
>
> end
> end
>
>
> I'm not sure exactly how to incorporate what you said. My attempt to try and incorporate a Rxnew=Rxlast+Rx, but I couldn't get the labelling right (I think this is similar to what you said about keeping track of present position. Then, my next thought was that maybe I could somehow return the result vectors from the loop to create a matrix and then sum over all x's, y's and z's to find net displacement, but I can't figure out a way to do that w/the loop present. Either way, if you could help enlighten/walk me through this a little, it would be greatly appreciated. Thank you.

Subject: Matlab 3-d Walk problem

From: Steven Lord

Date: 6 Nov, 2013 15:06:51

Message: 18 of 18


"Vivekananda Bal" <124026003@iitb.ac.in> wrote in message
news:l5dgps$8$1@newscl01ah.mathworks.com...
> Hi everybody, I am presently working on lattice modelling, where we have
> to move aparticle in 3D randomly along the sides of a cubic lattice. I
> want to create a random unit vector along the lattice (6 possible ways of
> moving the particle). I am little bot confused about it. Can you guys
> please suggest me a suitable way?

Generate two random numbers. The first is one of 1, 2, or 3 and represents
the dimension in which the particle walks. The second is +1 or -1 and
represents the direction the particle walks in that dimension. You can use
RANDI to do this; the second number will require a tiny amount of
adjustment. [If the particle can stand still, that would eliminate the need
to adjust RANDI's output for the second case.]

If your lattice is finite, you will need to handle the case where you're at
the edge of the cube.

Rather than calling RANDI twice at each step to generate scalar values, I'd
generate a large number of steps ahead of time with two RANDI calls then use
the steps as you need them.

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us