Working in Matlab with random walks. This is my code to plot the distance of 500
ID: 3750314 • Letter: W
Question
Working in Matlab with random walks. This is my code to plot the distance of 5000 random walkers in histograms at times t1=100, t2=200 and t3=300. I was wondering if someone could help me condense some of the lines to make it neater (the repeated parts in the for loop and then again with the subplots at the end). Been trying it for a couple of hours with no luck. Thanks.
_________________
Here is the rw function called in the below script:
function[x,y] = rw(t)
x = zeros(1,t+1);
y = zeros(1,t+1);
for i = 1:t
ang = 2*pi*rand(1);
x(i+1) = x(i)+cos(ang);
y(i+1) = y(i)+sin(ang);
end
________________________
The Script:
n=5000;
t1=100;
t2=200;
t3=300;
xt1=zeros(1,n);
yt1=zeros(1,n);
xt2=zeros(1,n);
yt2=zeros(1,n);
xt3=zeros(1,n);
yt3=zeros(1,n);
for i = 1:n
[x,y] = rw(t1);
xt1(i)=x(t1+1);
yt1(i)=y(t1+1);
d1(i) = hypot(xt1(i), yt1(i));
end
for i = 1:n
[x,y] = rw(t2);
xt2(i)=x(t2+1);
yt2(i)=y(t2+1);
d2(i) = hypot(xt2(i), yt2(i));
end
for i = 1:n
[x,y] = rw(t3);
xt3(i)=x(t3+1);
yt3(i)=y(t3+1);
d3(i) = hypot(xt3(i), yt3(i));
end
f1 = subplot(1,3,1);
hist(d1, 1:2:50)
f2 = subplot(1,3,2);
hist(d2, 1:2:50)
f3 = subplot(1,3,3);
hist(d3, 1:2:50)
Explanation / Answer
Keeping the rw function untouched. I have done some changes in the script to condense the code.
function[x,y] = rw(t)
x = zeros(1,t+1);
y = zeros(1,t+1);
for i = 1:t
ang = 2*pi*rand(1);
x(i+1) = x(i)+cos(ang);
y(i+1) = y(i)+sin(ang);
end
________________________
Improvised Script:
n=5000;
t = [100 200 300];
x = [zeros(1,n) zeros(1,n) zeros(1,n)];
y = [zeros(1,n) zeros(1,n) zeros(1,n)];
t = t';
for i = 1:n
for j = 1:3
[xn,yn] = rw(t(j));
x(j,i)=xn(t(j)+1);
y(j,i)=yn(t(j)+1);
d(i,j) = hypot(x(j,i), y(j,i));
end
end
f1 = subplot(1,3,1);
hist(d(:,1), 1:2:50)
f2 = subplot(1,3,2);
hist(d(:,2), 1:2:50)
f3 = subplot(1,3,3);
hist(d(:,3), 1:2:50)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.