File Exchange

image thumbnail


version (1.36 KB) by Robert Rasche
iterate cell array contents without clutter

1 Download

Updated 22 Nov 2017

View License

The "each"-utility allows to iterate the contents of a cell array using a for-loop almost like one would do with any numeric or struct array that isn't in cells.
Normally, when using a for loop, the cell array is passed to the loop variable in columns (that are Nx1-cell arrays).

for elem = {'a', 'list', 'of', 'words'}
class(elem) % -> cell
size(elem) % -> 1x1
disp(elem{1}); % need unpack

This is inconvenient, when using only row-vector lists of things. One would want the for-loop to directly assign the 1x1-colum-cell's content to the loop variable. Passing the cell through the constructor of the "each"-utility, you can achieve just that.

for elem = each({'a', 'list', 'of', 'words'})
class(elem) % -> char
size(elem) % -> 1xN (length of word)
disp(elem); % need not unpack

It also looks very clean, i think.

One restriction is, that "each" will pass out the contents of all n*m 1x1-cells of the original nxm-cell-array one after another, rather than passing a column at a time - there is after all only one variable to receive the result. For clarity, you should therefore only use it with row-vectors.

Under the hood, "each" is a thin class (whos instances are only temporary). It wraps the cell-array containing the data and provides size- and subsref-handlers that suite the way MATLAB internally does for-loops.

Cite As

Robert Rasche (2021). each (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (2)

Robert Rasche

@Jeremy Hughes: I like the idea of it being only one simple file. I don't need the genericity and abstract base class and being able to implement custom iterators. For me this is only about avoiding the explicit unpacking.

I had been using a similar thing (also using subsref-override) at my company, which was part of some (strongly hated) library at my company. Now I only need this one feature on a regular basis. I also hope that some day, MATLAB will have a for-loop syntax suitable for cells also.

The question could be, why I bothered uploading my new "each" to here.

Jeremy Hughes

I think you've recreated: I'd love to hear why you wrote your own.

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

Inspired by: For-Each

Community Treasure Hunt

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

Start Hunting!