File Exchange

## For-Each

version 1.01 (28.4 KB) by
Tools for simplifying for-loops. Customizable loop iteration.

Updated 25 Apr 2017

Editor's Note: This file was selected as MATLAB Central Pick of the Week

The for-each tools enable simple, readable, and powerful for loops in MATLAB(R).
For example, you can:
* Loop over the contents of a cell array without using braces for indexing,
* Convert an arbitrarily nested for-loop to a single loop using eachCombination,
* Loop through slices of an N-D array along any dimension(s),
* Loop over large numbers of permutations of a vector,
* Define your own rules for iterating over an array.
(Works from release R2009b)

### Cite As

Jeremy Hughes (2021). For-Each (https://www.mathworks.com/matlabcentral/fileexchange/48729-for-each), MATLAB Central File Exchange. Retrieved .

Jan Kappen

@Dmitri Khokhlov,
you're comparison is not fair, this is 1e5 loop iterations vs 1. Use `for e=a(:)'; s=s+1; end`. However, for each is still much slower (3 seconds vs 3 milliseconds on my PC).

It gets a bit better skipping the strcmp checks in Toolboxes\For-Each\+each\+iterators\Iterable.m, (down to 2 seconds) however that obviously reduces robustness. We could probably cache some information here.

The issue is, that the function calls can't be compiled just in time I guess.

Quintessence: don't use each() in tight loops. But for non-tight loops I use it a lot.

Dmitri Khokhlov

This is great, a must have feature in moderns languages now days.
Jeremy - any chance to have it built into Matlab language?
Because this solution is slow:
>> a = zeros(1, 1e5);
>> s = 0;
>>
>> tic;for e = each(a), s = s + 1; end;toc;
Elapsed time is 5.978914 seconds.
>> tic;for e = a(:), s = s + 1; end;toc;
Elapsed time is 0.000819 seconds.

Jan Kappen

I love it, but we cannot use or improve it because of the license. Please, are there any plans to use a more permissive license?

Robert Cox

I agree with Christopher, please consider releasing this under a more permissive license such as MIT, BSD, or Apache 2.0. The current license is extremely restrictive.

selcuk caglar

Christopher Dembia

Please consider using a permissive license (Apache, MIT, BSD) for this code so that as many people could use it as possible!

Chang hsiung

great tool, thanks a lot

Christopher Dembia

This is awesome. I am part of a C++ project that provides a MATLAB interface through Java (and SWIG). In C++, we have a linked-list container that can only be accessed through an iterator. In MATLAB, people can use this container via "it = list.begin(); while ~it.equals(list.end()); it.next(); end" but this is very bug-prone. I would love to use your library to implement our own iterator and to allow our users to use the "for item = each(list)" syntax.

It would be great if this could be released under a more open license (like Apache 2.0) so that I could incorporate it into my project. Otherwise, we will be unable to use this fantastic package.

Clemens Nyffeler

Clemens Nyffeler

It would be useful to be able to iterate fields of a structure:

for field = eachField(struct)

end

Clemens Nyffeler

Philip Ohnewein

Slow for large arrays, but generally this is extremely useful! Also consider Paul Kaefer's eachFile -> see his comment in the "pick of the week" article.

Matthew

Brian

Thanks, I am very happy to see this!

I wonder about the efficiency though. Keeping all the caveats about the pointlessness and difficulties with micro-benchmarking and pre-mature optimization in mind, for a simple micro-benchmark the "each" iteration seemed almost a couple orders of magnitude slower when looping over a cell array:

%gen a big cell array
num_cells = 100000;
max_num = 100000000;

arr = cellstr(num2str(randi(max_num,num_cells,1)+100000));

for repeat=1:5
tic;
tot_len = 0;
for i = 1:num_cells
tot_len = tot_len + length(arr{i});
end
toc
tot_len

tic;
tot_len = 0;
for val = each(arr)
tot_len = tot_len + length(val);
end
toc
tot_len
end

last elapsed times:
Elapsed time is 0.067018 seconds.
Elapsed time is 4.681804 seconds.

Jeremy Hughes

Hi Ray, I believe the eachColumn function will do what you are looking for with most arrays. That's an interesting suggestion for iterating through tables. Thanks!

ray

Can add the feature to iterate over some columns in an array or somes subtaables in a table by a row index?
It's useful to work about table.

such as:
A = rand(5,2); %or a table
idx = [1 1 2 2 3]'; %or a categorical array
for i=unique(idx)
elm=A(idx==i,:);
...
end

Clayton Chu

There isn't a language feature I wanted more in MATLAB than a foreach loop. Now I have one. This makes development so much easier!

##### MATLAB Release Compatibility
Created with R2014b
Compatible with any release
##### Platform Compatibility
Windows macOS Linux

Inspired: each

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!