使用for循环遍历一个空矩阵 [英] Iterating an empty matrix using a for loop

查看:132
本文介绍了使用for循环遍历一个空矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我始终认为,使用循环循环的空向量迭代与完全没有循环相同。然而,我偶然发现了这个奇怪的行为:

pre $ for t = []%//迭代一个空的0x0矩阵
1
end
for t = ones(1,0)%//迭代一个空的1x0矩阵
2
end
for t = ones(0,1) %//迭代一个空的0x1矩阵
3
end

结果是:

  ans = 
3

是否有意义,或者这是一个错误?

解决方案

for 循环在其输入的所有列上运行。由于一个0x1矩阵有一个(空)列,所以循环将简单地遍历它。没有提到空矩阵的例外,所以这里 t 将只是空矩阵,如下所示:

<$ p $ (0,1)%//迭代一个空的0x1矩阵
size(t)%t是一个0x1矩阵
结束
/ code>

这是一个错误吗?
可能不是。

是否有意义?那么,我想我宁愿循环不执行,如果输入是空的,但也可能有这个好处。



至少这是肯定的东西警惕!


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?

解决方案

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!

这篇关于使用for循环遍历一个空矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆