For loop with multiplication step in MATLAB

*爱你&永不变心* 提交于 2019-12-02 21:09:37

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/10019838/for-loop-with-multiplication-step-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!