Python matrix manipulation with numpy module

Asked

Viewed 6,338 times

2

How do I exchange lines of matrices, using numpy?

I need this to implement the Gauss-Jordan method of linear systems solution with partial pivoting.

1 answer

2


If by "exchange" you mean transpose rows x columns, you do so:

import numpy as np

teste = np.array([i for i in range(1,41)]).reshape((10,4))
print('Normal:')
print(teste)

print('Transposta:')
print(teste.T)

Upshot:

Normal:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]
 [17 18 19 20]
 [21 22 23 24]
 [25 26 27 28]
 [29 30 31 32]
 [33 34 35 36]
 [37 38 39 40]]
Transposta:
[[ 1  5  9 13 17 21 25 29 33 37]
 [ 2  6 10 14 18 22 26 30 34 38]
 [ 3  7 11 15 19 23 27 31 35 39]
 [ 4  8 12 16 20 24 28 32 36 40]]

If, on the other hand, you mean "exchange" one line for the other, then you do so:

import numpy as np

teste = np.array([i for i in range(1,41)]).reshape((10,4))
print('Normal:')
print(teste)

print('Permutada:')
salva = np.copy(teste[1])
teste[1] = teste[5]
teste[5] = salva
print(teste)

Upshot:

Normal:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]
 [17 18 19 20]
 [21 22 23 24]
 [25 26 27 28]
 [29 30 31 32]
 [33 34 35 36]
 [37 38 39 40]]
Permutada:
[[ 1  2  3  4]
 [21 22 23 24]
 [ 9 10 11 12]
 [13 14 15 16]
 [17 18 19 20]
 [ 5  6  7  8]
 [25 26 27 28]
 [29 30 31 32]
 [33 34 35 36]
 [37 38 39 40]]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.