raising an element of a vector to a power gives complex number, but it should be real number
11 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Stephen23
2024-3-16
编辑:Stephen23
2024-3-16
"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 个评论
Steven Lord
2024-3-16
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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Exponents and Logarithms 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!