Home > OS >  I was trying to use matrixes without libraries but I can't set the values correctly
I was trying to use matrixes without libraries but I can't set the values correctly

Time:07-24

def create_matrix(xy):
    matrix = []
    matrix_y = []
    x = xy[0]
    y = xy[1] 
    for z in range(y):
        matrix_y.append(0)
    for n in range(x):
        matrix.append(matrix_y)
    return matrix

def set_matrix(matrix,xy,set):
    x = xy[0] 
    y = xy[1] 
    matrix[x][y] = set
    return matrix

index = [4,5]
index_2 = [3,4]

z = create_matrix(index)

z = set_matrix(z,index_2, 12)
print(z) 

output:

[[0, 0, 0, 0, 12], [0, 0, 0, 0, 12], [0, 0, 0, 0, 12], [0, 0, 0, 0, 12]]

This code should change only the last array

CodePudding user response:

In your for n in range(x): loop you are appending the same y matrix multiple times. Python under the hood does not copy that array, but uses a pointer. So you have a row of pointers to the same one column.

Move the matrix_y = [] stuff inside the n loop and you get unique y arrays.

Comment: python does not actually have a pointer concept but it does use them. It hides from you when it does a copy data and when it only copies a pointer to that data. That's kind of bad language design, and it tripped you up here. So now you now that pointers exist, and that most of the time when you "assign arrays" you will actually only set a pointer.

Another comment: if you are going to be doing anything serious with matrices, you should really look into numpy. That will be many factors faster if you do numerical computations.

CodePudding user response:

you don't need first loop in create_matrix, hide them with comment:

#for z in range(y):
#    matrix_y.append(0)

change second one like this, it means an array filled with and length = y:

for n in range(x):
    matrix.append([0] * y)

result (only last cell was changed in matrix):

z = set_matrix(z,index_2, 12)
print(z)

# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 12]]
  • Related