Reputation:
In MATLAB the following for
loop:
for i = [1:100]'
%'// Do something, such as disp(i)
end
isn't apparently really implemented by iteration, rather i
becomes the matrix [1 2 3 ... 100] and the "loop" is only executed once on this matrix i
. You can verify this by printing the value of i
or other tracking information. Only a single pass is made through the loop.
Is it possible to force MATLAB to do genuine looping? The reason I ask is that the above approach is fine for many cases but much more painful when you have nested loops that need to run.
Example:
The following code won't do what you would expect if you thought you were getting actual iteration over a loop:
for i = outlier
data(i) = median(data(i-100:i+100))
end
One would expect at each outlier index this would replace data(i) with the median of the data from i-100 to i+100, but it doesn't. In fact, the median returns a single value computed on a conglomerate of all the ranges you cared about, and every data(i) point is replaced with that single value.
Upvotes: 7
Views: 3218
Reputation: 74930
If you write
for i = (1:100)' %'# square brackets would work as well
doSomething
end
the loop is executed only once, since a for
-loop iterates over all columns of whatever is to the right of the equal sign (it would iterate 200 times with a 100-by-200 array to the right of the equal sign).
However, in your example, you have i=[1:100]
, which evaluates to a row vector. Thus, the loop should execute 100x.
If you iterate over an array that might be nx1
instead of 1xn
, you can, for safety reasons, write:
for i = myArray(:)' %'# guarantee nx1, then transpose to 1xn
end
Upvotes: 12
Reputation: 27017
This is not correct. The code:
for i=1:100
disp(i)
end
will print all the values 1 through 100 consecutively. While Matlab does encourage vectorization, you can definitely use traditional loops with the style of coding you used above.
Upvotes: 7