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

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?

Answers


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.


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.


Need Your Help

Text editors with vim mode?

vim text-editor viemu

I've come across ViEmu, and I read the very motivating article: Why, oh WHY, do those #?@! nutheads use vi?

I get "Source not found" when debugging my Java code in Eclipse

java eclipse debugging

I'm trying to debug my Java application in Eclipse however when I hit a breakpoint I simply see the following instead of my source: