Reputation: 124
I was trying to write a code that can do elementary row operations on matrices and I have run into some issues. I realize that there are libraries that have functions that can be used to complete these operations; however, I am doing this for my own gratification.
The problem arises with the replacement operation. The intended purpose of this operation is to replace a row by the sum of itself and the multiple of another row. For example, if I have a matrix [[1,2,3],[2,1,3],[3,2,1]] , I want to replace the top row (the row [1,2,3]) with the sum of itself and the second row (the row [2,1,3]) multiplied by a factor of 2. I would like the code to give me: [[5,4,9],[2,1,3],[3,2,1]]
When I enter this particular matrix, the answer I get is: [[5, 4, 9], [4, 2, 6], [3, 2, 1]]
My code is as follows:
def multiply_row(matrix,row_num,factor):
#Let row_num = 1 indicate the top row
temp_row = matrix[row_num - 1]
entries = len(matrix[row_num - 1])
current_term = 0
while current_term < entries:
temp_row[current_term] = temp_row[current_term] * factor
current_term = current_term + 1
return temp_row
def replacement(matrix,rowA,rowB,factor):
#Replace 1 row be by the sum of itself and a multiple of another row
#rowA is the row being replaced
#rowB is being multiplied by the factor
#Let rowA = 1 indicate the top row
temp_rowB = multiply_row(matrix,rowB,factor)
entries = len(matrix[rowA - 1])
current_term = 0
while current_term < entries:
matrix[rowA - 1][current_term] = temp_rowB[current_term] + matrix[rowA - 1][current_term]
current_term = current_term + 1
return matrix
m = [
[1,2,3],
[2,1,3],
[3,2,1]
]
print replacement(m, 1, 2, 2)
Clearly, the problem lies within my “multiply_row” function. I created this function so that I could create a temporary place where I can multiply a row by a factor, without actually affecting the row in the matrix itself. This is not working.
I was wondering if someone could explain why this temporary row is actually altering the row in the matrix itself. Also, I realize that I am probably not doing the operation in the most efficient way possible and I would be curious to know what the more efficient way to do it would be (this is only secondary, I would really appreciate an answer to my first question).
Thank you for the help
Upvotes: 0
Views: 43
Reputation: 25548
The problem is that temp_row
is not a copy of the row in your matrix but a reference to it. Anything you do to temp_row
therefore happens to the corresponding row in your matrix, since it is happening to the same object (which happens to be referenced in two different ways). Replace the line in multiply_row()
with
temp_row = matrix[row_num - 1][:]
to make a copy. You then get:
[[5, 4, 9], [2, 1, 3], [3, 2, 1]]
as you required.
Upvotes: 1