Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

matlab - Iterating an empty matrix using a for loop

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...