bug in for loop?

1 次查看(过去 30 天)
itamar luzon
itamar luzon 2018-4-30
评论: Jan 2018-4-30
matlab run this code like there is a space between "5" and "a" in "for ii=4:5a" line.
a='aaaa';
for ii=4:5a
disp(ii);
end
answer:
a =
'aaaa'
4
a =
'aaaa'
5
while matlab cannot read a simpler line like:
5a
answer:
5a
Error: Unexpected MATLAB expression.
  2 个评论
Dennis
Dennis 2018-4-30
what is 5a supposed to be? I am pretty sure it is no valid Matlab expression.
Jan
Jan 2018-4-30
@Dennis: Obviously the Matlab interpreter considers the code as valid. "5a" is not supposed to be a variable, but Matlab interprets this as "for ii=4:5 a".
@itamar luzon: I can imagine, that it took you a while to identify this behavior. A nice and confusing observation. Thanks for posting it, +1.

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2018-4-30
Cute. ;-)
While it is not what I would expect, I am not sure it could be called a bug.
The "for" loop can be followed by a statement on the same line:
for i = 4 : 5 disp(a), end
The parsing of the range of values for the "for" loop proceeds as far as possible to form an expression.
>> for j = 4:5i
disp(j)
end
Warning: Colon operands must be real scalars.
"i" is a valid numeric suffix so it was included in the parsing.
Now, what it it appears is that once it has gone as far as it can in parsing the expression for the loop bounds, that it is prepared to pick up from the very next character as the expression to be executed, without requiring a whitespace or ';' or ',' . Not what I would have guessed, but in the absence of any documentation saying that whitespace or separator is mandatory there, it is difficult to call it a bug.
... One thing that you need to understand is that the MATLAB command parser is hacked together. The MATLAB language "just grew" and was not defined in terms of BNF, so there are parsing oddities in corner cases like these.
  1 个评论
itamar luzon
itamar luzon 2018-4-30
Thanks, Walter.
I agree it's not a bug, but it still very confusing.
"Not what I would have guessed", I also agree about the guess, I also thought the same, but in programming, things need to be clear and we don't need to guess.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by