Line exchange in the matrix

Asked

Viewed 1,446 times

3

Hello. I was programming in python and wanted to change the line (between the second and third lines) of an array using the following code. But I wanted to know why the variable auxLinha changes value when modified b[inicio]

def trocaLinhaB(b,inicio,final):
    listaAux = b[inicio]
    b[inicio] = b[final]
    b[final] = listaAux

The original matrix

0 2 3
0 -3 1
2 1 5

But the result was

[[ 0.  2.  3.]
 [ 0. -3.  1.]
 [ 0. -3.  1.]]

and I expected the

[[ 0.  2.  3.]
 [ 2.  1.  5.]
 [ 0. -3.  1.]]

1 answer

3


I believe you’re using the library numpy, therefore, the variable listaAux stores only a display of the matrix and not the data (and therefore, it "changes" the value).

When you change the matrix, also change the view.

One possible solution to this problem is to store a copy of the data in the variable listaAux before making the replacement.

The function code is as follows::

def trocaLinhaB(b,inicio,final):
    listaAux = b[inicio].copy()  # <= aqui: cria uma cópia
    b[inicio] = b[final]
    b[final] = listaAux

Browser other questions tagged

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