필터 지우기
필터 지우기

Why do I get error incorrect use of '=' operator?

조회 수: 8 (최근 30일)
현우 이
현우 이 2020년 6월 19일
댓글: 현우 이 2020년 6월 19일
I made the drunk man simulation. But if I run this, I get the error message Error: Incorrect use of '=' operator. To assign a value to a variable, use '='. To compare values for equality, use '=='.
and if I change = to <=, I get the error message
while (s<10 && s >-10 && i<100)
Error: Illegal use of reserved keyword "while".
Why does this happen and how can I fix it? Thanks a lot in advance.
This is my code.
alive = 0
success = 0
dead = 0
p = 0.5
for n=1:1000
{
i = 0
s = 0
while (s<10 && s >-10 && i<100)
x = rbinom(1, 1, p);
if(x == 1)
s = s-1;
else
s = s+1;
i = i+1;
end
if(s == 10)
success = success + 1;
end
if(s == -10)
dead = dead + 1;
end
end
if(s<10 &&s > -10)
alive = alive +1;
end
barplot(c(success, dead, alive))

채택된 답변

Nipun Agarwal
Nipun Agarwal 2020년 6월 19일
Hey,
The problem comes in because of curly braces after the for loop. MATLAB syntax never allows curly braces after the for loop. I have updated the code of yours and indented it properly for you to have a better standing.
alive = 0;
success = 0;
dead = 0;
p = 0.5;
for n=1:1000
i = 0;
s = 0;
while (s<10 && s >-10 && i<100)
x = 1;
if(x == 1)
s = s-1;
else
s = s+1;
i = i+1;
end
end
if(s == 10)
success = success + 1;
end
if(s == -10)
dead = dead + 1;
end
if(s<10 &&s > -10)
alive = alive +1;
end
end
barplot(c(success, dead, alive))
  댓글 수: 2
Stephen23
Stephen23 2020년 6월 19일
The MATLAB Editor's default indentation rules give this even clearer version:
alive = 0;
success = 0;
dead = 0;
p = 0.5;
for n=1:1000
i = 0;
s = 0;
while (s<10 && s >-10 && i<100)
x = 1;
if(x == 1)
s = s-1;
else
s = s+1;
i = i+1;
end
end
if(s == 10)
success = success + 1;
end
if(s == -10)
dead = dead + 1;
end
if(s<10 &&s > -10)
alive = alive +1;
end
end
barplot(c(success, dead, alive))
현우 이
현우 이 2020년 6월 19일
Thank you!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by