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

8 次查看(过去 30 天)
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))

请先登录,再进行评论。

更多回答(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