-1
>> a = [1 1 2 3 5 8 13 21 13 37];
>> d = [1 2];
>> w = [0 0 0];
  for e = d
      g = 0;
      for f = a
          if mod (f, 2) == 0
              g = [g f];
          end
      end
w = [w;g];
end
>> w

The output of W is the matrix

0     0     0
0     2     8
0     2     8

My question is about the for-loops. Do Matlab for-loops take a value, instead of being a logical condition? For example, when looking at 'for f = a' does f take the value of the array A and then the for-loop iterates through F by its columns?

Thanks.

1

2 Answers 2

3

FOR loops have a variable, each pass through the loop the iterator variable takes on the next value in the array. The iterator variable takes on the values of the columns, one at a time. The right hand side of the assignment statement in the foor loop needn't be a numeric array -- it could be a cell array of strings for example, or a structure, etc.

In other words, when you have for

for f=a, ....., end

this is equivalent to writing

for i=1:numel(a)/size(a,1); f=a(:,i); .... ; end

You can easily see this by adding some disp statements into your code:

for e = d
      disp(e)
      g = 0;
      for f = a
          disp(f)
          if mod (f, 2) == 0
              g = [g f];
          end
      end
w = [w;g];
end

WHILE loops in matlab take a logical condition.

(edit: i forgot that f takes on the value of the columns of a if a is multidimensioned)

0
1

Yes, MATLAB loop variables are assigned to "arrays", called vectors in MATLAB parlance. The value of the loop variable automatically iterates over elements of the vector upon each iteration of the loop. A common construct is

for i=1:10 %generates vector of 1,2,...,10
i %will print i=1, i=2, etc.
end

In this case the vector was generated on the fly, and is sequential numbers. But there is no reason you can't pass any arbitrary vector in to iterate over, like "a" in your case. Upon each iteration, "f" takes on the next value in the sequence contained in "a".

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.