For loop with multiplication step in MATLAB

Go To StackoverFlow.com

0

Is there any way to use a for-loop in MATLAB with a custom step? What I want to do is iterate over all powers of 2 lesser than a given number. The equivalent loop in C++ (for example) would be:

for (int i = 1; i < 65; i *= 2)

Note 1: This is the kind of iteration that best fits for-loops, so I'd like to not use while-loops.
Note 2: I'm actually using Octave, not MATLAB.

2012-04-04 21:57
by Paul Manta


5

Perhaps you want something along the lines of

for i=2.^[1:6]
   disp(i)
end

Except you will need to figure out the range of exponents. This uses the fact that since a_(i+1) = a_i*2 this can be rewritten as a_i = 2^i.

Otherwise you could do something like the following

i=1;
while i<65
   i=i*2;
   disp(i);
end
2012-04-04 22:15
by Azim


3

You can iterate over any vector, so you can use vector operations to create your vector of values before you start your loop. A loop over the first 100 square numbers, for example, could be written like so:

values_to_iterate = [1:100].^2;
for i = values_to_iterate
   i
end

Or you could loop over each position in the vector values_to_iterate (this gives the same result, but has the benefit that i keeps track of how many iterations you have done - this is useful if you are writing a result from each loop sequentially to an output vector):

values_to_iterate = [1:100].^2;
for i = 1:length(values_to_iterate)
   values_to_iterate(i)
   results_vector(i) = some_function( values_to_iterate(i) );
end

More concisely, you can write the first example as simply:

for i = [1:100].^2
   i
end

Unlike in C, there doesn't have to be a 'rule' to get from one value to the next. The vector iterated over can be completely arbitrary:

for i = [10, -1000, 23.3, 5, inf]
     i
end
2012-04-04 22:19
by Bill Cheatham
Ads