Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Matlab 3-d Walk problem
Date: Mon, 22 Nov 2010 06:06:03 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 29
Message-ID: <icd18b$ftq$1@fred.mathworks.com>
References: <ic4j4j$oqf$1@fred.mathworks.com> <icbp5r$6f9$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1290405963 16314 172.30.248.35 (22 Nov 2010 06:06:03 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 22 Nov 2010 06:06:03 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1708920
Xref: news.mathworks.com comp.soft-sys.matlab:688867

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