Reputation: 4855
I have this function that returns a numpy
array with two vectors that represent x
and y
coordinates respectively, and I want to turn them into (x;y) pairs.
For example:
import numpy as np
def rotate(coords, angle, center=(0, 0,)):
rotated = np.array([np.cos(np.radians(angle)) * (coords[:,0] - center[0]) - np.sin(np.radians(angle)) * (coords[:,1] - center[1]) + center[0],
np.sin(np.radians(angle)) * (coords[:,0] - center[0]) + np.cos(np.radians(angle)) * (coords[:,1] - center[1]) + center[1]])
return rotated
xy = np.array([[1,2],[3,4],[5,6],[6,7]])
a = rotate(xy,20)
print a
This gives me:
[[ 0.25565233 1.45099729 2.64634224 3.24401472]
[ 2.22140538 4.78483091 7.34825644 8.62996921]]
However, I actually want this output:
[[0.25565233, 2.22140538]
[1.45099729, 4.78483091]
[2.64634224, 7.34825644]
[3.24401472, 8.62996921]]
Upvotes: 1
Views: 109
Reputation: 104464
Simply take the transpose. You can use numpy.transpose
or you can use the overloaded operator .T
:
xy = np.array([[1,2],[3,4],[5,6],[6,7]]);
a = rotate(xy,20).T # <--- Modification here
Doing this thus gives:
>>> print a
[[ 0.25565233 2.22140538]
[ 1.45099729 4.78483091]
[ 2.64634224 7.34825644]
[ 3.24401472 8.62996921]]
If you want to avoid transposing the output, you can let the function do that. Just transpose what is returned inside your rotate
function:
def rotate(coords, angle, center=(0, 0,)):
rotated = np.array([np.cos(np.radians(angle)) * (coords[:,0] - center[0]) - np.sin(np.radians(angle)) * (coords[:,1] - center[1]) + center[0],
np.sin(np.radians(angle)) * (coords[:,0] - center[0]) + np.cos(np.radians(angle)) * (coords[:,1] - center[1]) + center[1]])
return rotated.T #<-- Modification here
You can thus do what you did before without thinking about it further:
xy = np.array([[1,2],[3,4],[5,6],[6,7]]);
a = rotate(xy,20)
... which gives us:
>>> print a
[[ 0.25565233 2.22140538]
[ 1.45099729 4.78483091]
[ 2.64634224 7.34825644]
[ 3.24401472 8.62996921]]
Upvotes: 3
Reputation: 90869
You want to transpose it -
In [3]: n = np.array([[ 0.25565233, 1.45099729, 2.64634224 , 3.24401472],
...: [ 2.22140538 , 4.78483091 , 7.34825644 , 8.62996921]])
In [4]: n
Out[4]:
array([[ 0.25565233, 1.45099729, 2.64634224, 3.24401472],
[ 2.22140538, 4.78483091, 7.34825644, 8.62996921]])
In [6]: n.T
Out[6]:
array([[ 0.25565233, 2.22140538],
[ 1.45099729, 4.78483091],
[ 2.64634224, 7.34825644],
[ 3.24401472, 8.62996921]])
In your case -
def rotate(coords, angle, center=(0, 0,)):
rotated = np.array([np.cos(np.radians(angle)) * (coords[:,0] - center[0]) - np.sin(np.radians(angle)) * (coords[:,1] - center[1]) + center[0],
np.sin(np.radians(angle)) * (coords[:,0] - center[0]) + np.cos(np.radians(angle)) * (coords[:,1] - center[1]) + center[1]])
return rotated
xy = np.array([[1,2],[3,4],[5,6],[6,7]])
a = rotate(xy,20)
print a.T
>> [[ 0.25565233 2.22140538]
[ 1.45099729 4.78483091]
[ 2.64634224 7.34825644]
[ 3.24401472 8.62996921]]
Upvotes: 1