Setting boundaries of a for loop

Hi, I would like to alter my code so that the random values that I get for position do not excced past a certian point. I would like these values to be no greater than 20 and no smaller than -20 and fit into this range of numbers for 1000 points. How can I write this? Thanks so much, I'm relatively new to Matlab.
position= zeros(1,1000);
position(1)=0;
tails = 0;
heads= 1;
for s=(2:1000)
x= randi([0 1]);
if x==tails
position(s)= position(s-1)-1;
elseif x==heads
position(s)= position(s-1)+1;
end
end

댓글 수: 2

madhan ravi
madhan ravi 2018년 11월 26일
but the random numers that you are generating is 0 and 1?
Maybe I worded this question wrong, but what I'm trying to do is stop the size of the position from getting too big or too small by creating a domain. So let's just say if my value x was always equal to 1 or heads, then the position would continue to keep increasing by 1 until it reaches 1000 right? So what if I wanted to make it so that the position would never get bigger than a specified number like 20.
position= zeros(1,1000);
position(1)=0;
tails= 0;
heads=1;
for s=(2:1000)
x=1
if x==tails
position(s)=position(s-1)-1;
elseif x==heads
position(s)position(s-1)+1;
end

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

답변 (1개)

Matt J
Matt J 2018년 11월 26일

0 개 추천

position(s) = min(position(s-1)+1 , 20);

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2018년 11월 26일

답변:

2018년 11월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by