8

I was wondering what the rule is for using vectors as range in for-loop in Matlab?

For example,

range = [0.1:0.01:2]'; % wrong
range = [0.1:0.01:2]; % correct

for i = range
i
end
  1. Why is it that if range is column vector, it will not work, while if range is row vector, it will?
  2. Will i = range be interpreted as i taking each value of range, or i is assigned with vector range?

Thanks~

3 Answers 3

11

More generally, range can be a matrix, and the loop variable loops over its columns.

range = rand(3,3);
for col = range
col
end

col =
      0.86341
      0.11625
      0.20319
col =
      0.59721
     0.098357
       0.8356
col =
      0.89578
      0.46217
      0.93585

So if range is a row vector, it will loop over its values. But if range is a column vector, it will loop over that single column as its value.

Sign up to request clarification or add additional context in comments.

Comments

3

From http://www.mathworks.co.uk/help/techdoc/ref/for.html:

for index = values
   program statements
          :
end

... values has one of the following forms:

valArray

creates a column vector index from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1)...

Comments

0
  1. It's that way because it's that way. I don't think that there is any deep explanation for this.
  2. As you would discover if you experimented, once you've made an assignment such as range = [0.1:0.01:2] then the variable called range is a row-vector comprising the values in the range. Your loop will work just fine. As it would if it started

    for i = [0.1 0.11 0.12 ...]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.