nightcod3r
nightcod3r

Reputation: 792

A for loop to browse (without an index variable) the elements of a cell array in GNU Octave / Matlab

Given a cell array, say c = {'first', 'second', 'third'}, how can it be browsed in a for loop without using an index?

This can be done for arrays, so for c = [1, 2, 3], this would work:

for k = c
  ...         # use k here as an element of c
endfor

What is the equivalent, elegant way, for a cell array? (Please, note that a cell array is not always transformable into an array.)

Update: It actually works fine as it is (i.e., when c is a cell array), but only if the values are stored in a row; it won't work when stored in a column, like c = {'first'; 'second'; 'third'}.

Upvotes: 3

Views: 1769

Answers (1)

beaker
beaker

Reputation: 16791

Here are a couple of options:

If the individual elements of c are transformable to an array, you can use the indices as the loop variable:

for k = 1:numel(c)
   disp(c{k}); 
end

first
second
third

This option is closest to what cellfun would do. (cellfun would be another option to replace the for loop entirely.)

If the elements are not transformable to an array (or you just want to do it a different way) you can use c as the loop index and grab the contents inside the loop:

for k = c
   disp(k{});
end

first
second
third

This is the most direct translation of what you do in your example.

Upvotes: 4

Related Questions