Raise a scalar to a descending series of powers in an array

조회 수: 14 (최근 30일)
Bill Tubbs
Bill Tubbs 2020년 8월 17일
편집: Steven Lord 2020년 8월 17일
I'm trying to compute a series of powers of a scalar.
This seems to work but the result is not what I expected:
0.8^1:3
ans =
0.8000 1.8000 2.8000
I expected:
ans =
0.8000 0.6400 0.5120
(It looks like it is returning 0.8:3)
This therfore doesn't work either:
0.8^3:-1:1
ans =
1×0 empty double row vector
Neither does this
0.8^(3:-1:1)
Error using ^ (line 51)
Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar. To perform elementwise matrix powers, use '.^'.
Neither of these work
0.8^[3 2 1]
0.8^[1 2 3]
Error using ^ (line 51)
Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar. To perform elementwise matrix powers, use '.^'.
So, how do I compute the scalar to the power of a series of descending values?

채택된 답변

Bill Tubbs
Bill Tubbs 2020년 8월 17일
Here is the correct answer I think. Element-wise operation:
0.8.^(3:-1:1)

추가 답변 (2개)

Steven Lord
Steven Lord 2020년 8월 17일
편집: Steven Lord 2020년 8월 17일
Your 0.8^1:3 example doesn't do what you think it does.
>> x1 = 0.8^1:3
>> x2 = [0.8^1 0.8^2 0.8^3]
x1 =
0.8 1.8 2.8
x2 =
0.8 0.64 0.512
The power operations in MATLAB are at operator precedence level 2 and 3, while the colon operator is at level 7. So your expression (which I used to define x1 above) is the equivalent of:
(0.8^1):3
What you want is to wrap the colon expression in parentheses. But if you try making that change alone you receive an error (line breaks added to avoid scroll bars.)
>> x3 = 0.8^(1:3)
Error using ^ (line 51)
Incorrect dimensions for raising a matrix to a power.
Check that the matrix is square and the power is a scalar.
To perform elementwise matrix powers, use '.^'.
So since you want to perform elementwise matrix powers, use the .^ operator instead of the ^ operator.
>> x4 = 0.8.^(1:3)
x4 will match x2.

Bill Tubbs
Bill Tubbs 2020년 8월 17일
편집: Bill Tubbs 2020년 8월 17일
I found this solution:
power(0.8,3:-1:1)
ans =
0.5120 0.6400 0.8000
But still surprised if it can't be done with the ^ operator.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by