Reputation: 333
I'm trying to implement pivoting for the Gaussian elimination in Python and face some problems.
def pivot2(matrix,i):
# matrix is a N*N matrix
# i is the column I want to start with
m = matrix.shape[1]
for n in range(i,m):
colMax = np.argmax(abs(matrix[n:,i]), axis=0) #rowindex of highest absolute value in column
if(colMax == 0): #if max in column is in first row, stop
break;
tmpRow = copy.copy(matrix[n,:]) #create new object of same row
matrix[n,:] = matrix[colMax,:] #overwrite first row with row of max value
matrix[colMax,:] = tmpRow #overwrite old row of max value
return matrix
The code works for i=0
just fine. However for i=1
I can't search for the index of the maximum value in the whole column because it will obviously always be 0
.
When I slice this matrix from a 3x3 matrix:
array([[ 1., 2.],
[-3., -2.]])
and use my argmax
function, the index is 1
. But in my original matrix the index of the same row is 2 and it swaps the wrong rows. How do I fix this?
And is there a simpler way to implement pivoting using slices?
Upvotes: 4
Views: 2308
Reputation: 117510
You just have to add i
to colmax
after checking for 0:
...
if(colMax == 0): #if max in column is in first row, stop
break;
colmax += i # add this string
...
Upvotes: 2