MATLAB: Do I get error incorrect use of ‘=’ operator

==

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))

Best Answer

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))
Related Question