Greg Peckory
Greg Peckory

Reputation: 8068

Finding solutions to row reduced matrix python

Suppose I have a reduced Matrix in this form:

   x    y    z    =
[[2.0, 4.0, 4.0, 4.0], 
 [0.0, 2.0, 1.0, 2.0], 
 [0.0, 0.0, 1.0, 1.0], 
 [0.0, 0.0, 0.0, 0.0]]

And I want an array containing the solutions.

In this case I'd want to return

  z    y     x
[1.0, 0.5, -1.0]

We can assume it is a perfect triangle with no free variables.

I was looking at scipy.linalg.solve to solve, but it requires the form Ax=B and I'm not sure how to convert to this form.

Upvotes: 3

Views: 3772

Answers (2)

B. M.
B. M.

Reputation: 18668

Remark than :

     [2.0, 4.0, 4.0, 4.0]  x     0
     [0.0, 2.0, 1.0, 2.0]  y  =  0
     [0.0, 0.0, 1.0, 1.0]  z     0
     [0.0, 0.0, 0.0,-1.0]  t     1

has the same solution, with t=-1.

So let I=np.eye(4)and b=I[3]. the solution is then given by :

In [2]: solve(A-I*b,b)[:-1]
Out[2]: array([-1. ,  0.5,  1. ])

Upvotes: 1

miradulo
miradulo

Reputation: 29720

You already have all of the information you need to use numpy.linalg.solve. A is represented by the first 3 columns of your 2d array, and b is the last column. Hence if you slice your array into those elements respectively, you can call .solve. Note that I sliced off the last row such that your system becomes well-determined, as numpy.linalg.solve requires a well-determined system:

init_array = numpy.array(
        [[2.0, 4.0, 4.0, 4.0],
         [0.0, 2.0, 1.0, 2.0],
         [0.0, 0.0, 1.0, 1.0],
         [0.0, 0.0, 0.0, 0.0]])

A = init_array[0:3,:-1]
b = init_array[0:3, -1]
x = numpy.linalg.solve(A, b)
print(x)

Outputs:

[-1.   0.5  1. ]

Further reading:

Upvotes: 5

Related Questions