raising an element of a vector to a power gives complex number, but it should be real number
6 views (last 30 days)
Show older comments
Hello guys could you please help me with something, I have a very weird error.
I have a vector of data L_tilda, which I have created by taking logs and the applying HP filter to a vector of raw data. I wanted then to raise this vector element wise to the power 0.35.
The issue is, when I do that the results are complex numbers. But when I raise just the number, identical to the element of the vector, the result is real number.
Below I provide the output of the console, when I try to raise just one element of a vector to the power 0.35
>> L_tilda{end,2}
ans =
-0.007345972038603
>> L_tilda{end,2} ^ 0.35
ans =
0.081313753652337 + 0.159587227160134i
>> -0.007345972038603 ^ 0.35
ans =
-0.179108932233131
0 Comments
Answers (1)
Stephen23
on 16 Mar 2024
Edited: Stephen23
on 16 Mar 2024
"Oh okay I guess I got it..."
No guessing is required, this is explained by the rules of operator precedence:
It is clearly shown that matrix power has higher precedence than unary negation, so your code:
-0.007345972038603 ^ 0.35
is exactly equivalent to this:
-(0.007345972038603 ^ 0.35)
This is completely different to
n = -0.007345972038603;
n ^ 0.35
which is equivalent to
(-0.007345972038603) ^ 0.35
2 Comments
Steven Lord
on 16 Mar 2024
Yes, that's the expected behavior, as Stephen23 explained.
If you want MATLAB to apply unary minus (to create a negative number) before raising that value to a power, you must either define the negative number as a variable or wrap the negative number in parentheses (which has higher precedence than the power operator.)
In precedence order parentheses are first (level 1), the power operators are the next two (levels 2 and 3), and unary minus (-x) is after that (level 4.) If you remember in school learning the mnemonics PEMDAS or BODMAS, the documentation page Stephen23 linked to is the equivalent in MATLAB.
The two sections of code that create x1a and x1b below behave the same:
format longg
x1a = -0.007345972038603 ^ 0.35 % is the same as
x1b = uminus(power(0.007345972038603, 0.35))
while the code that creates x2a, x2b, and x2c behave the same.
x2a = (-0.007345972038603) ^ 0.35 % is the same as
n = -0.007345972038603;
x2b = n^0.35 % and the same as
x2c = power(uminus(0.007345972038603), 0.35)
See Also
Categories
Find more on Exponents and Logarithms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!