Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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:

for t = []          %// Iterate an empty 0x0 matrix
    1
end
for t = ones(1, 0)  %// Iterate an empty 1x0 matrix
    2
end
for t = ones(0, 1)  %// Iterate an empty 0x1 matrix
    3
end

The result is:

ans =
    3

Does it make sense, or is this a bug?

share|improve this question

1 Answer 1

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!

share|improve this answer
3  
+1: Good answer to a good question! – Eitan T Jul 30 '13 at 15:34
2  
+1 For surprises with empty matrices... – bla Jul 30 '13 at 15:40
    
do you mean for t = t' ? – Try Hard Jul 30 '13 at 15:43
    
@TryHard My question was edited and someone removed the v. I have updated the answer to match. – Dennis Jaheruddin Jul 30 '13 at 15:45
    
@DennisJaheruddin - This was something I wasn't aware about, and this makes total sense. Thanks for this tidbit of information! – rayryeng Jul 14 '14 at 18:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.