16

I have a python code in which I have to convert a 2D array to a 2D matrix so that I can use it to calculate inverse.For that I am using numpy.matrix(array) but it is not working. Can anyone tell how to convert a 2D array to a numpy matrix? The array consists of all float numbers

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
abcdxx
  • 207
  • 1
  • 3
  • 12

2 Answers2

29

If a is your array, np.asmatrix(a) is a matrix.

Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221
  • error File "C:\xampp\htdocs\webdev\123.py", line 47, in print A.I File "C:\Python27\lib\site-packages\numpy\matrixlib\defmatrix.py", line 859, in getI return asmatrix(func(self)) File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 1574, in pinv u, s, vt = svd(a, 0) File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 1278,in svd a =_fastCopyAndTranspose(t, a) File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 145, in _fastCopyAndTranspose cast_arrays = cast_arrays + (_fastCT(a.astype(type)) ValueError: setting an array element with a sequence. – abcdxx Jul 03 '13 at 13:02
  • 9
    @abcdxx Come on, you can't just bomb me with a bunch of error messages, especially not without context. _What_ gives you this error, what parameters did you pass to which function etc? – Tobias Kienzler Jul 03 '13 at 13:08
  • I hv a 2D list I converted it to array using np.array and then further calculated inverse from matrix using A.I where A=np.asmatrix(array) but it gave the above error – abcdxx Jul 03 '13 at 13:13
  • 1
    Why don't you convert that list directly into a matrix? Anyway, you probably should post a minimum working example in a new question about this error, if you can't find it via google. – Tobias Kienzler Jul 03 '13 at 13:14
  • So you got an answer [there](http://stackoverflow.com/a/17449883/321973), and as you can see `.asmatrix` was used – Tobias Kienzler Jul 04 '13 at 08:12
2

If you have a list of lists (as you mentioned), you need to convert it first to a numpy array; see how to convert 2d list to 2d numpy array?

A short example is given here:

import numpy as np
a = [[  0. +0.j,   1.j,   2. -2.j],
     [  4. -4.j,   5. -5.j,   6. -1.j],
     [  8. -8.j,   9. -9.j,  10.]]
b = np.matrix(np.array(a))
b_inv = np.linalg.inv(b)
Community
  • 1
  • 1
strpeter
  • 2,562
  • 3
  • 27
  • 48