Alex Rivera | Logout

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

Asked 2009-01-02T21:28:47.877
183

Is there a foreach structure in MATLAB? If so, what happens if the underlying data changes (i.e. if objects are added to the set)?

Edit
Report

3 Answers

97

Zach is correct about the direct answer to the question.

An interesting side note is that the following two loops do not execute the same:

for i=1:10000
  % do something
end
for i=[1:10000]
  % do something
end

The first loop creates a variable i that is a scalar and it iterates it like a C for loop. Note that if you modify i in the loop body, the modified value will be ignored, as Zach says. In the second case, Matlab creates a 10k-element array, then it walks all elements of the array.

What this means is that

for i=1:inf
  % do something
end

works, but

for i=[1:inf]
  % do something
end

does not (because this one would require allocating infinite memory). See Loren's blog for details.

Also note that you can iterate over cell arrays.

answered 2009-01-03T04:43:42.630
7

When iterating over cell arrays of strings, the loop variable (let's call it f) becomes a single-element cell array. Having to write f{1} everywhere gets tedious, and modifying the loop variable provides a clean workaround.

% This example transposes each field of a struct.
s.a = 1:3;
s.b = zeros(2,3);
s % a: [1 2 3]; b: [2x3 double]
for f = fieldnames(s)'
    s.(f{1}) = s.(f{1})';
end
s % a: [3x1 double]; b: [3x2 double]

% Redefining f simplifies the indexing.
for f = fieldnames(s)'
    f = f{1};
    s.(f) = s.(f)';
end
s % back to a: [1 2 3]; b: [2x3 double]
answered 2009-07-28T19:55:00.233
4

I think this is what the OP really wants:

array = -1:0.1:10

for i=1:numel(array)
    disp(array(i))
end
answered 2011-10-28T02:49:37.497

Your Answer