Reputation: 375
Lets say the given matrix would be:
A = array([[ 5., 6., 4., 1.],
[-4., -1., -7., -4.],
[ 2., -3., 9., 8.]])
and I want to raise the matrix A
to the power p = 1.05
.
For positive integers it is not a problem, but I want to raise the negative numbers too to the p power with pretending the negative sign (otherwise the numbers will be nan
in numpy).
Here is the example of A_pow = A**p
:
A_pow = array([[ 5.41899193, 6.56234129, 4.28709385, 1. ],
[ nan, nan, nan, nan],
[ 2.07052985, nan, 10.04510857, 8.87655578]])
My approach was something like this (for the matrix B
):
B = A.copy()
B[B > 0.0] = B[B > 0.0]**p
B[B < 0.0] = -np.abs(B[B < 0.0])**p
Which gives me:
B = array([[ 5.41899193, 6.56234129, 4.28709385, 1. ],
[ -4.28709385, -1. , -7.71530221, -4.28709385],
[ 2.07052985, -3.16940193, 10.04510857, 8.87655578]])
Is there any other or better way to approach the same goal?
Upvotes: 2
Views: 479
Reputation: 402483
(np.abs(A) ** 1.05) * np.sign(A)
array([[ 5.41899193, 6.56234129, 4.28709385, 1. ],
[ -4.28709385, -1. , -7.71530221, -4.28709385],
[ 2.07052985, -3.16940193, 10.04510857, 8.87655578]])
np.sign
retrieves the sign of each element. Then, convert the array to its absolute with np.abs
, find the power, and multiply by the sign mask.
Upvotes: 4