Trying to solve use Gauss elimination to solve


I’ve tried solving the matrix using gauss elimination, and as far as I know, the first portion of the code is correct, but I’m not sure I’m calling the matrix correctly

Hi Dave, and welcome!

Unless you use Photoshop to edit your source code, please don’t post pictures of code. Please copy the code as text, and paste it between “code fences”, three backticks on a line of their own:

```
your code goes here
```

You can also use three tildes ~~~ instead of the backticks.

Continuing the discussion from Trying to solve use Gauss elimination to solve:

Thanks for the notice Steven, here’s the code.

import numpy as np
import copy
from numpy import c_

def GaussNaive(A,b):
    'solve Ax=b using Naive Gauss elimination'
    A=A.astype(np.float64) ; b=b.astype(np.float64)
    m,n = A.shape
    if m != n:
        print('Matrix A must be square')
        return
    m1,n1 = b.shape
    if m1 != m:
        print('b and A must have the same number of rows')
        return
    Aug = c_[A,b]
    nm1 = n-1; np1 = n+1
    for i in range(nm1):
        for j in range(i+1,n):
            fac = Aug[j,i]/Aug[i,i]
            for k in range(i,np1):
                Aug[j,k] += -Aug[i,k]*fac
    x=np.zeros(shape=b.shape)
    x[nm1]=Aug[nm1,n]/Aug[nm1,nm1]
    for i in range(nm1-1,-1,-1):
        s=0
        for k in range (i+1,n):
            s += x[k]*Aug[i,k]
        x[i]=(Aug[i,n]-s)/Aug[i,i]
    print('\n {x} ='); print(x)
    return x

if __name__ == '__problem_4__':
    A=[[1, 1, -1],
      [6, 2, 2],
      [-3, 4, 1]]
    b=[-3, 2, 1]
    print(GaussNaive(A,b))

The values of A and b that are being passed into GaussNaive are lists of lists, so A.astype(np.float64) and b.astype(np.float64) aren’t going to work because lists don’t have a .astype method.

They need to be converted to numpy arrays first:

A = np.array(A).astype(np.float64)
b = np.array(b).astype(np.float64)