Can the “s{1} annoyance” when iterating over a cell array be avoided?

前端 未结 2 1744
不思量自难忘°
不思量自难忘° 2021-02-12 08:05

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 enclosi         


        
2条回答
  •  不知归路
    2021-02-12 08:45

    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.

提交回复
热议问题