Skillful way to loop with index and value in matlab

Many of my loops look like this:

items = [3,14,15,92]; for item_i = 1:numel(items) item = items(item_i); % ... end 

It looks a little dirty to me. Is there any loop construct that allows me to iterate over the elements and wrap the index at the same time?

I am looking for syntax along the lines for item_i as item = items or for [item_i item] = items .

+8
matlab
source share
4 answers

Like Chris Taylor, you can do this:

 function [ output ] = Enumerate( items ) output = struct('Index',num2cell(1:length(items)),'Value',num2cell(items)); end items = [3,14,15,92]; for item = Enumerate(items) item.Index item.Value end 

The Enumerate function will require additional work for general purposes, but it starts and works for your example.

This would be good for small vectors, but you would not want to do this with any meaningful vectors, since performance would be a problem.

+7
source share

I believe that there is no way to do this. The trick I used in the past is to exploit the fact that Matlab iterates over the columns of a matrix, so you can define an enumerate function that adds an index row to the beginning of the matrix:

 function output = enumerate(x) output = [1:size(x,2); x]; end 

and then use it like this:

 for tmp = enumerate(items) index = tmp(1); item = tmp(2:end); end 

but this is actually no better than what you originally did. It would be nice if in Python you could something like

 for [index,item] = enumerate(items) # loop body end 

where enumerate is a function that returns two matrices of the same length, but ... you cannot.

+5
source share

I will sometimes do something like this

 arr = {'something', 'something else'}; arrayfun(@(x, y)sprintf('%s (item %i)', x{:}, y), arr, 1:length(arr), ... 'UniformOutput', false) 

But this is only useful in very specific situations (in particular, in those situations where you would use arrayfun to shorten the syntax), and to be honest, you usually do this at the beginning, probably better for most cases - nothing else probably confusing your intentions.

+2
source share

Will this work for you?

 k = 0; for ii = items k = k + 1; %% The index item = ii; % ... end 

Hope this helps.

+1
source share

All Articles