这个“{1}烦恼”可以吗?当迭代一个单元格数组是可以避免的? [英] Can the "s{1} annoyance" when iterating over a cell array be avoided?

查看:156
本文介绍了这个“{1}烦恼”可以吗?当迭代一个单元格数组是可以避免的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题的 s {1} 烦恼引用下面for-block的第一行:

  for s = some_cell_array 
s = s {1}; %unpeel封闭单元
%做s
结束

这个<因为迭代 some_cell_array 并不真正遍历<$ c>的内容,所以code> s = s {1} $ c> some_cell_array ,而是超过1个元素 ,每个元素包含 some_cell_array 中的项目。



把这个行为作为默认的 可能的问题放在一边,是否有任何方法来遍历 em> bare some_cell_array ?

解决方案

在一般情况下,不要认为有办法避免这个问题。但是如果你的单元格数组有全部的数字或者所有的字符,那么有一个办法。你可以转换成一个数组,并让循环循环。



例如: p>

  some_cell_array = {1,2,3} 
for s = [some_cell_array {:}]%转换为数组
s
end

给出:

$ p $ s

s =

另一种选择是创建一个在数组的每个单元上运行的函数。然后,您只需致电 cellfun 并没有任何循环。



对于谁会想要这个行为或者如何有用,我没有任何想法。然而,我为什么以这种方式工作的猜测是它是一个实现的东西。这样循环迭代器不会在不同的迭代中改变类型。这是一个单元格,即使该单元格的内容是不同的类型。


The "s{1} annoyance" of the title refers to the first line within the for-block below:

for s = some_cell_array
    s = s{1};  % unpeel the enclosing cell
    % do stuff with s
end

This s = s{1} business is necessary because the iteration over some_cell_array does not really iterate over the contents of some_cell_array, but rather over 1-element cells, each containing an item from some_cell_array.

Putting aside the question of who could possibly want this behavior as the default, is there any way to iterate over the bare contents of some_cell_array?

解决方案

I don't think there is a way to avoid this problem in the general case. But there is a way if your cell array has all numbers or all chars. You can convert to an array and let the for loop iterate over that.

For example, this:

some_cell_array = {1,2,3}
for s = [some_cell_array{:}] % convert to array
    s
end

Gives:

s =
     1
s =
     2
s =
     3

Another option is to create a function that operates on every cell of the array. Then you can simply call cellfun and not have a loop at all.

I don't have any ideas about who would want this behavior or how it could be useful. My guess as to why it works this way, however, is that it's an implementation thing. This way the loop iterator doesn't change type on different iterations. It is a cell every time, even if the contents of that cell are different types.

这篇关于这个“{1}烦恼”可以吗?当迭代一个单元格数组是可以避免的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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