A basic MATLab question regarding iterations

68 Views Asked by At

Suppose I want to run a loop for integers $i = 2,2^2,2^3, \dots,2^n$

How would I do this? That is, suppose I want to evaluate some function f(i) through the increments $2, 2^2, 2^3$. I understand that for loops in MatLab can only take arithmetic difference step size, but not geometric ones.

2

There are 2 best solutions below

5
On BEST ANSWER

Just run the loop from $i=1\dots n$ and calculate the power of $2$ manually

Psuedocode:

k = 2
for 0:1:n-1
  k = k*2 
  do something
end
2
On

The easiest way in octave (Matlab is similar)

for k=1:n
    i=2^k;
     blah blah blah
end

If you really want to show off your Octave/Matlab skills, you can do this

for k=2.^(1:10), disp(k);end

Replace disp with your code

Note: For statement in Octave and Matlab takes a row vector. The syntax is

for variable=columns
    body
end

The variable iterates over the columns. The most common usage for columns is a:b