indexing a vector by a power
이전 댓글 표시
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?
채택된 답변
추가 답변 (2개)
Azzi Abdelmalek
2013년 9월 25일
0 개 추천
Why are you using if n = 0:9. what you need is a for loop
댓글 수: 6
dustin
2013년 9월 25일
Azzi Abdelmalek
2013년 9월 25일
post your code with a for loop
dustin
2013년 9월 25일
Azzi Abdelmalek
2013년 9월 25일
your for loop woks only for n=9, because you are erasing the previous result each iteration
If you have
n=1
pow=2^n
for the next iteration
n=2
power=2^n
What is the result?
dustin
2013년 9월 25일
Azzi Abdelmalek
2013년 9월 25일
Image Analyst
2013년 9월 25일
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
dustin
2013년 9월 25일
@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.
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!