vector is not overwritten after certain interation during loop

조회 수: 11 (최근 30일)
Dennis Trapp
Dennis Trapp 2019년 11월 10일
편집: KALYAN ACHARJYA 2019년 11월 10일
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

채택된 답변

Dennis Trapp
Dennis Trapp 2019년 11월 10일
update: closed matlab, restarted laptop, now it works
...classic trouble shooting :-D
anyway, thanks for the support (great community here) :)
  댓글 수: 1
KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 11월 10일
편집: KALYAN ACHARJYA 2019년 11월 10일
@Dennis
Glad to know that you resolved the issue. We're so happy you're here!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 11월 10일
편집: KALYAN ACHARJYA 2019년 11월 10일
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
Dennis Trapp
Dennis Trapp 2019년 11월 10일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile 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