Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using vector as range in for-loop In Matlab

Tags:

matlab

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~

like image 272
Tim Avatar asked May 14 '12 14:05

Tim


Video Answer


2 Answers

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.

like image 196
Sam Roberts Avatar answered Sep 20 '22 01:09

Sam Roberts


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)...

like image 22
Oliver Charlesworth Avatar answered Sep 21 '22 01:09

Oliver Charlesworth