I'm working with numpy using a matrix that is 1x3. My question is:
Exists a way to convert that matrix into a tuple that contains the elements of the matrix in order? For example, if the matrix is
A=matrix([[1,2,3]])
get
B=(1,2,3)
I'm working with numpy using a matrix that is 1x3. My question is:
Exists a way to convert that matrix into a tuple that contains the elements of the matrix in order? For example, if the matrix is
A=matrix([[1,2,3]])
get
B=(1,2,3)
Yes, you can do something as simple as this:
>>> A = matrix([[1,2,3]])
>>> B = A.tolist()
>>> B
[[1, 2, 3]]
>>> B = A.tolist()[0]
>>> B
[1, 2, 3]
EDIT:
As Christian points out, I see that you have changed your desired output to a tuple. As Christian suggests, all you need to do is this:
>>> B = tuple(A.tolist()[0])
>>> B
(1, 2, 3)
A
will still function as a matrix, but B
is now a tuple and so will not function as a matrix.
If you want get a list from 3x1, 1x3, use flatten
:
>>> from numpy import matrix
>>> matrix([[1,2,3]]).flatten().tolist()[0]
[1, 2, 3]
>>> matrix([[1],[2],[3]]).flatten().tolist()[0]
[1, 2, 3]
Alternative using A1
attribute:
>>> matrix([[1],[2],[3]]).A1.tolist()
[1, 2, 3]
>>> matrix([[1,2,3]]).A1.tolist()
[1, 2, 3]
How about this?
>>> import numpy as np
>>> m = np.matrix([[1,2,3]])
>>> m
matrix([[1, 2, 3]])
>>> B = tuple(m.A[0])
>>> B
(1, 2, 3)
Edit: Inspired by @falsetru's use of flatten
, this is a more general solution:
>>> tuple(m.A.flatten())
(1, 2, 3)
I think using flatten
on an array
makes more sense because it converts 2D array into 1D, while this cannot be done for matrices.