1

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)
iam_agf
  • 639
  • 2
  • 9
  • 20
  • 2
    Remember `(1,2,3)` is a tuple. A list would be `[1,2,3]` – Christian Tapia Dec 25 '13 at 04:28
  • But my problem is that the word 'matrix' exists and when you get something in the matrix, it still has the word 'matrix' at the start. – iam_agf Dec 25 '13 at 04:29
  • you can extract undelying array with `matrix([[1,2,3]]).A`, or flattened 1d underlying array with `matrix([[1,2,3]]).A1`, and work with them – alko Dec 25 '13 at 07:29

3 Answers3

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.

Justin O Barber
  • 11,291
  • 2
  • 40
  • 45
1

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]
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

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.

Akavall
  • 82,592
  • 51
  • 207
  • 251