Matlab equivalent of Python enumerate
As far as I know, there is no equivalent of enumerate in Matlab. The most common way to do this is:
for i = 1:length(foo_list)
item = foo_list(i);
% do stuff with i, item
end
Seems there is no equivalent in Matlab. However if you have a simple 1 x X array you can define it yourself (if you don't worry about performance):
enumerate = @(values) [1:length(values); values]
a = [6 5 4]
for i=enumerate(a)
do something with i
end
Of course the clean way would be to wrap this inside a general toolkit and add an assert that a is indeed a 1 x X vector.
It's easy to achieve by defining a new class for the iteration:
classdef enumerate < handle
properties(Access = private)
IterationList;
end
methods
function self = enumerate(in)
self.IterationList = in;
end
function [varargout] = subsref(self, S)
item = subsref(self.IterationList,S);
num = S.subs{2};
out.item = item;
out.num = num;
varargout = {out};
end
function [m,n] = size(self)
[m,n] = size(self.IterationList);
end
end
end
You can use it in this way:
for t = enumerate(linspace(0,1,10));
disp(['num is: ',num2str(t.num),'item is: ',num2str(t.item)]);
end
And will get this output:
num is: 1item is: 0
num is: 2item is: 0.11111
num is: 3item is: 0.22222
num is: 4item is: 0.33333
num is: 5item is: 0.44444
num is: 6item is: 0.55556
num is: 7item is: 0.66667
num is: 8item is: 0.77778
num is: 9item is: 0.88889
num is: 10item is: 1