Reputation: 41
close all;
hold on
%Edited
M = zeros(100,500);
%
for count = 0:99
x = [];
p = 0;
for i = 1:499
n = rand(1);
if n > 0.5
p = p+1;
end
if n < 0.5
p = p-1;
end
x(i) = p;
end
%Edited
for j = 1:500
M(n,j) = x(j);
end
%
X = abs(x);
Y = 1:length(X);
ps = csapi(X,Y);
fnplt(ps)
end
hold off
grid on
title('Random Walk Distances')
xlabel('Distance from the Origin')
ylabel('Each Iteration of the Experiment')
My intent is to find a mean curve of all the curves plotted by the code. To do so I'm thinking of finding the mean value for each index of the array's then plotting that curve, however, I'm only keeping the value of the last iteration how can I store all values in a large matrix.
Edit : I've surrounded the change I was thinking in (%) but it doesn't work. States :
Error in Random_walk_1D (line 30)
M(n,j) = x(n);
Subscript indices must either be real positive integers or logicals.
Upvotes: 0
Views: 38
Reputation: 899
The main idea in your code is not bad, however you are mixing variable names and indexes, and not all your loops are as long as your vectors.
For example:
your first loop goes over the variable count
for count = 0:99
...
end
but in the second sub loop you are trying to assign to M(n,j)
for j = 1:500
M(n,j) = x(j);
end
however your variable n
is assigned to a random number. You should change this to:
for j = 1:500-1
M(count+1,j) = x(j);
end
As you see I also had to decrease the number of elements to 500-1
as x
has only 499 entries:
for i = 1:499
....
end
I recommend you try not to hard code it, but rather use variables:
close all;
hold on
%Edited
m1=100;
m2=499;
M = zeros(m1,m2);
for count = 0:m1-1
x = [];
p = 0;
for i = 1:m2
n = rand(1);
if n > 0.5
p = p+1;
end
if n < 0.5
p = p-1;
end
x(i) = p;
end
%Edited
for j = 1:m2
M(count+1,j) = x(j);
end
X = abs(x);
Y = 1:length(X);
ps = csapi(X,Y);
fnplt(ps)
end
hold off
grid on
title('Random Walk Distances')
xlabel('Distance from the Origin')
ylabel('Each Iteration of the Experiment')
I recommend you to put your script in to a function and run this.
Once you get an error, put a break point at this place and have a look how your variables/index look like, to understand why this error comes. This will help you to debug your code yourself.
Upvotes: 1