Borrar filtros
Borrar filtros

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

9 visualizaciones (últimos 30 días)
현우 이
현우 이 el 19 de Jun. de 2020
Comentada: 현우 이 el 19 de Jun. de 2020
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))

Respuesta aceptada

Nipun Agarwal
Nipun Agarwal el 19 de Jun. de 2020
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 comentarios
Stephen23
Stephen23 el 19 de Jun. de 2020
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))
현우 이
현우 이 el 19 de Jun. de 2020
Thank you!

Iniciar sesión para comentar.

Más respuestas (0)

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by