简体   繁体   中英

for loop range syntax

I spent a couple of hours debugging a problem that I would have thought would have been a syntax error.

a = zeros(3);
for i=1:1size(a,2) % note the missing colon between 1 and size(a,2)
    i
end

The following only displays

ans = 3
1

Essentially, it seems Matlab/Octave parses the above as:

for i=1:1
    size(a,2)
    i
end

Note however that

i=1:1size(a,2)

produces a syntax error. Is there a good reason that Matlab/Octave has this for loop syntax? Is there something that it's supposed to make easier? Just curious if anyone else has any thoughts about it. Thanks.

It is indeed a bit of a surprise that Matlab's syntax allows this. I don't know why this is allowed. One reason might be to allow for-loops on one line:

>> for i=1:3 disp(i);end
     1
     2
     3

But interestingly, removing the space is not allowed:

>> for i=1:3disp(i);end
 for i=1:3disp(i);end
        |
Error: Unexpected MATLAB operator.

This reason for this is probably that a number followed by d is another way of writing a floating point number ( 3d10 == 3e10 ), so the parser/tokenizer initially thinks you define a number, but then gets confused when it sees the i . Daniel's example with fprintf does work, since a number followed by an f is not a valid number, so the tokenizer understands that you started a new token.

I guess that many years ago (>30?), when they defined matlab's syntax, they did not foresee that this could introduce this kind of hard-to-spot problems. I guess matlab was originally written by engineers for engineers, and not by someone who knows how to design a general purpose programming language. Other languages like C or Python use punctuation to separate loop conditions from loop body, so there is no ambiguity. I don't know if it is still possible to correct Matlab's syntax, since it might break old code that relies on the current behavior.

At least, if you use a recent version of Matlab, the editor warns for various problems in your code. Paying attention to the small red dashes in the right hand border could have saved you a few hours of debugging time (but maybe you were using octave). I try to make it a habit to fix all the warnings it indicates. For your code, it shows the following:

编辑截图

Your code is equivalent to

a = zeros(3);
for i=1:1
    size(a,2)
    i
end

There are some places where everyone would use newline or white space, but the parser itself does not require.

A minimal loop:

for i=1:3fprintf('%d',i),end

but I recommend to use at least a comma seperated version, everything else is horrible to read:

for i=1:3,fprintf('%d',i),end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM