Converting a problem from Mathematica to MATLAB
3 ビュー (過去 30 日間)
古いコメントを表示
I have this problem in mathematica and want to do it in MATLAB.
steps[m_] := Table[2 RandomInteger[] - 1, {m}]
Walk1D[n_] := FoldList[Plus, 0, steps[n]]
LastPoint1D[n_] := Fold[Plus, 0, steps[n]]
nsteps = 200; nsq = Floor[Sqrt[nsteps]];
MeanSquareDistance1D[n_Integer, m_Integer] :=
N[Sum[LastPoint1D[n]^2, {m}]/m]
r2D=MeanSquareDistance1D[100, 1000]
data = Map[({#, MeanSquareDistance1D[#,2000]})&,
Range[10, 90, 20]]
This is what i did :
steps=@ (m) randi(3,1,m)-2;
Walk1D =@ (n) cumsum(steps(n));
LastPoint1D = @ (Walk1D) (Walk1D(end));
nsteps=200;
nsq=floor(sqrt(nsteps));
MeanSquareDistance1D= @ (n,m) sum((LastPoint1D(n)).^2)./m;
r2D=MeanSquareDistance1D(100,1000)
data=zeros(5,2);
for i=10:20:90
data=[i,MeanSquareDistance1D(i,2000)]
end
The problem is 1) r2D gives me the same value as many times as i run the code,but it must change. 2) In the "data " the first column its ok (its 10:20:90) but the 2nd column gives me the same numbers as i run the code. And,also,i don't know if i defined it right(the "data")
EDITED CODE -------------------------
steps=@ (m) 2*randi([0,1],[1,m])-1;
Walk1D =@ (n) [0,cumsum(steps(n))];
findend=@ (x) x(end);
LastPoint1D=@(n) findend(Walk1D(n));
nsteps=200;
nsq=floor(sqrt(nsteps));
MeanSquareDistance1D= @ (n,m) m.*sum((LastPoint1D(n)).^2)./m;
r2D=MeanSquareDistance1D(100,1000)
data=[ ];
for i=10:20:90
data=[data; i , MeanSquareDistance1D(i,2000)]
end
EDIT-->>>
I did it like this(with help):
steps1=@ (n, m) randi([-1 1], n, m);
LastPoint_1D=@ (n, m) sum(steps1(n, m));
MeanSquareDistance1D = @(n,m) mean(LastPoint_1D(n,m).^2);
2 件のコメント
回答 (2 件)
Seth DeLand
2011 年 2 月 21 日
George,
Looks like there's a problem with this line of code:
LastPoint1D = @ (Walk1D) (Walk1D(end));
I believe what you are trying to do is call the 'Walk1D' function and find the last element of the vector that is returned by 'Walk1D'. Here is one way to do that:
findend = @(x) x(end);
LastPoint1D = @ (n) findend(Walk1D(n));
The 'findend' function just takes in a vector and returns the last element of that vector. Try replacing your line of code above with the two lines I suggested and let me know if that helps.
12 件のコメント
Oleg Komarov
2011 年 2 月 22 日
I found this article "One Dimensional RW", and referring to the paragraph "The root mean square distance from the origin after a random walk of n unit steps is ?n.", I derived the following function:
function Out = MeanSquareDistance1D(n,m)
% Create random walk with unit steps
Walk1D = [0 cumsum(2*randi([0,1],[1,m])-1)];
% Plot it
% plot(Walk1D)
% Means square distances from the origin for all steps
Out = Walk1D.^2./(1:m+1);
% Select just the steps at n intervals
Out = Out(n:n:m);
end
Or in handle fmt:
Walk1D = @(m) [0 cumsum(2*randi([0,1],[1,m])-1)];
MeanSquareDistance1D = @(n,m) Walk1D(m).^2./(1:m+1);
Oleg
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!