Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - for loop over cell array "foreach"-like syntax loops only over the first element [duplicate]

I thought that if I write

for x = cell_array
    ...
end

then the loop will run over the elements of cell_array, but in the following case it doesn't:

>> tags

tags = 

    'dset3'
    'dset4'
    'cpl1'

>> class(tags)

ans =

cell

>> for t = tags
     tmp = t{:}  %No semicolon: i.e. print it.
   end

tmp =

dset3

So it only works for the first element.

What's the problem?

like image 933
Evgeni Sergeev Avatar asked May 31 '26 09:05

Evgeni Sergeev


1 Answers

According to the documentation, for x = cell_array will iterate over columns of the cell array.

The reason for the confusion in the question is to do with how the {:} expansion behaves:

>> a = {3;4}

a = 

    [3]
    [4]

>> b = a{:}

b =

     3

In the above, a{:} does something akin to typing in a comma-separated list where the elements are the elements of the cell array a. Except not quite! If we write such a list explicitly, we get:

>> c = 3,4

c =

     3


ans =

     4

Somehow, with the >> b = a{:}, the other elements of a are discarded silently, even if e.g. a = {1 2; 3 4}.

However, in other contexts, a{:} will expand into the full comma-separated list:

>> extra_args = {'*-'; 'linewidth'; 30};
>> plot(1:2, extra_args{:})
>> extra_args = {};
>> plot(1:2, extra_args{:})

This will do what it's intended to do.

like image 190
Evgeni Sergeev Avatar answered Jun 04 '26 00:06

Evgeni Sergeev