vector is not overwritten after certain interation during loop

Hi guys,
I tried to write a small function to perform a random walk.
I've struggled with a strict vector formulation, so I created some mixture.
However, it works until the an certain interation loop, after that, the step directions (here stpx and stpy) are not overwritten whereas this is the case during the first interations.
The effect appears randomly between the 5th and 10th interation step.
Although k is changing, stpx and stpy are not.
"num" is my matrix with random numbers between 1 and 4
k in the loop takes for each iteration values from "num" and generates a new 5x1 vector for each interation
the idea was that stpx/stpy is computed each time again using the valid k-vector for the interation step.
function [x,y,num]=random_walk(n,x0,y0)
num=randi([1 4],5,n);
x(5,1)=x0;
y(5,1)=y0;
stpx(1)=-1;
stpx(2)=0;
stpx(3)=0;
stpx(4)=1;
stpy(1)=0;
stpy(2)=1;
stpy(3)=-1;
stpy(4)=0;
stpx_0=0;
stpy_0=0;
x(5,n+1)=0;
y(5,n+1)=0;
k0=0;
for a=1:n
k=k0+num(:,a);
stpx= stpx_0+[stpx(k(1,1));stpx(k(2,1));stpx(k(3,1));stpx(k(4,1));stpx(k(5,1))];
stpy= stpy_0+[stpy(k(1,1));stpy(k(2,1));stpy(k(3,1));stpy(k(4,1));stpy(k(5,1))];
x(:,a+1)=x(:,a)+stpx;
y(:,a+1)=y(:,a)+stpy;
end
end
Is this an issue because stpx and stpy have no indices?
Thank you all for the your help with this issue.
Kind regards, Dennis

 采纳的回答

update: closed matlab, restarted laptop, now it works
...classic trouble shooting :-D
anyway, thanks for the support (great community here) :)

1 个评论

@Dennis
Glad to know that you resolved the issue. We're so happy you're here!

请先登录,再进行评论。

更多回答(1 个)

for a=1:n
k=k0+num(:,a);
stpx(a)= stpx_0+[stpx(k(1,1));stpx(k(2,1));stpx(k(3,1));stpx(k(4,1));stpx(k(5,1))];
stpy(a)= stpy_0+[stpy(k(1,1));stpy(k(2,1));stpy(k(3,1));stpy(k(4,1));stpy(k(5,1))];
x(:,a+1)=x(:,a)+stpx;
y(:,a+1)=y(:,a)+stpy;
end
Please note this iteration replace the stpx and stpy value ((Initializations)) until 1 to 4

1 个评论

Hi Kalyan,
thanks for the fast reply.
num is a 5xn matrix with values between 1 and 4
k calls for each iteration step 1:n (n=input, e.g. 10) the n-th colum from num
k is always a 5x1 vector with values from 1-4
this works fine within the loop (I checked it with section run) until the n-th iteration is reached

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

版本

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by