indexing a vector by a power

4 visualizaciones (últimos 30 días)
dustin
dustin el 25 de Sept. de 2013
I would like my vector to go by powers of 2 but everything I tried hasn't worked.
for n = 0:9
pow = (1:2^n:512)
end
but this doesn't return a vector with 1, 2, 4, 16, ...
What can I do to achieve this?

Respuesta aceptada

W. Owen Brimijoin
W. Owen Brimijoin el 25 de Sept. de 2013
You could accomplish this without using a for loop as follows:
n = 4;
p = 2.^cumprod([1,2+zeros(1,n-1)])
this results in:
p =
2 4 16 256
*Mind you, the start of the sequence you are asking for doesn't follow your own rules. Yes each element is the square of the previous one, except that 1^2 does not equal 2. So if you are intent on breaking that rule and want this sequence to start with a 1 and have n elements, then you would need to do this:
p = [1,2.^cumprod([1,2+zeros(1,n-2)])]
yielding:
p =
1 2 4 16

Más respuestas (2)

Azzi Abdelmalek
Azzi Abdelmalek el 25 de Sept. de 2013
Why are you using if n = 0:9. what you need is a for loop
  6 comentarios
dustin
dustin el 25 de Sept. de 2013
I don't want to erase the previous result each iteration. I want to put each step in a vector. How can I do this?
Azzi Abdelmalek
Azzi Abdelmalek el 25 de Sept. de 2013
For example
k=1
a(k)=2
k=2
a(k)=14
You have to read the getting started with Matlab

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 25 de Sept. de 2013
I don't know what happened to 2^3=8 - maybe it's missing, but if each element is the square of the previous element, this will do that and give you the output you gave:
p = [1, 2];
for k = 3 : 9
p(k) = p(k-1)^2;
end
% Display p
p
In the command window:
p =
Columns 1 through 7
1 2 4 16 256 65536 4294967296
Columns 8 through 9
1.84467440737096e+19 3.40282366920938e+38
On the other hand, this code seems to be more like what your code does, but does not give you the output you gave because the 8 is in there:
for k = 0 : 9
p(k+1) = 2^k;
end
% Display p
p
In the command window:
p =
1 2 4 8 16 32 64 128 256 512
  2 comentarios
dustin
dustin el 25 de Sept. de 2013
I need p to be a vector though.
Jan
Jan el 25 de Sept. de 2013
Editada: Jan el 25 de Sept. de 2013
@dustin: But p is a vector already.
These questions are such basic, that I suggest (as Azzi's did already) to read the Getting Started chapters of the documentation. The forum is not the right place to learn the fundamental usage of Matlab, because this has been done exhaustively by experts in the documentation already. If we re-tell what you can find there, too much time would be wasted.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by