Filter löschen
Filter löschen

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

8 Ansichten (letzte 30 Tage)
현우 이
현우 이 am 19 Jun. 2020
Kommentiert: 현우 이 am 19 Jun. 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))

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by