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

2
  • 1
    Inverse of Numpy matrix to array Commented Jul 3, 2013 at 8:55
  • 2
    You can also call np.linalg.inv on the array directly. Commented Jul 3, 2013 at 10:54

2 Answers 2

29

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

Sign up to request clarification or add additional context in comments.

5 Comments

error File "C:\xampp\htdocs\webdev\123.py", line 47, in <module> 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 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?
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
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.
So you got an answer there, and as you can see .asmatrix was used
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.