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

前端 未结 2 1746
不思量自难忘°
不思量自难忘° 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:51

    Just a small add-on to Sam Robert's comment to the original question, on why you should prefer s{:} over s{1} : easier bug tracking.

    Imagine you mistakenly stored your cell s as a column instead of a line. Then

    for s = some_cell_array
    

    will simply return a cell s which is equal to some_cell_array. Then the syntax s{1} will return the first element of some_cell_array, whereas s{:} will produce a list of all elements in some_cell_array. This second case will much more surely lead to an execution error in the following code. Whereas the first case could sometimes create a hard bug to detect.

提交回复
热议问题