Iterating an empty matrix using a for loop

后端 未结 1 1299
鱼传尺愫
鱼传尺愫 2020-12-16 11:00

I always assumed that iterating an empty vector using a for loop was the same as not having the loop at all. However, I stumbled upon this strange behavior:

相关标签:
1条回答
  • 2020-12-16 11:34

    The for loop runs over all columns of its input. Since a 0x1 matrix has one (empty) column, the loop will simply go over that. No exception is mentioned for empty matrices, so here t will simply be the empty matrix as seen from:

    for t = ones(0, 1) %// Iterate over an empty 0x1 matrix
        size(t) % t is a 0x1 matrix
    end
    

    Is it a bug? Probably not.
    Does it make sense? Well, I think I would prefer the loop not to execute if the input is empty, but probably there are advantages to this as well.

    At least it is definitely something to be alert of!

    0 讨论(0)
提交回复
热议问题