z has nsteps elements. k goes from 1 to nsteps. But in the loop you are trying to assign z(k+1), in other words, z(nsteps + 1). Try k = 1:(nsteps-1)
Info
此问题已关闭。 请重新打开它进行编辑或回答。
index exceeds matrix dimensions
1 次查看(过去 30 天)
显示 更早的评论
Hello, I've tried to do a reflecting random walk simulator 1d. I've did it first without the barrier and it graphs perfectly. However, when I tried adding reflecting barrier to it, it kept on producing the "index exceeds matrix dimension". Do you know what is causing the error? Thank you.
% This program will compute and plot the paths of a set of many
% random walkers, which are confined by a pair of barriers at +B and -B.
% Assume all walkers start at z = 0
nwalks = 10;
nsteps = 100;
figure;
hold on;
for j = 1:nwalks
x = randn(nsteps,1);
z = zeros(nsteps,1);
for k = 1:nsteps
% Reflecting barrier
B = 3;
if z(k+1) > B
z(k+1) = B - abs(B - z(k+1));
elseif z(k+1) < (-B)
z(k+1) = (-B) + abs((-B) - z(k+1));
end
z(k+1) = z(k) + x(k);
end
% Plot
plot(z);
xlabel('Time (step number)'), ylabel(' Distance');
hold off;
end
0 个评论
回答(1 个)
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!