Nakash - 6 months ago 40

Python Question

I was wondering what the for lines in this code are supposed to do. This is a snippet of code I need help with:

`# iterate through rows of X`

for i in range(len(X)):

# iterate through columns of Y

for j in range(len(Y[0])):

# iterate through rows of Y

for k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]

for r in result:

print(r)

Answer

This code multiplies matrices `X`

and `Y`

and puts the resulting product into matrix `result`

. It then prints the matrix `result`

row by row, so it looks like a matrix on the screen.

For this snippet to work, matrices `X`

, `Y`

and `result`

must already be set up--`X`

and `Y`

with their values, and `result`

with the right shape (numbers of rows and columns) but with meaningless values that will be overwritten.

The expression `len(X)`

returns the number of rows in `X`

, while `len(Y[0])`

returns the number of columns of `Y`

, at least if `X`

and `Y`

were set up properly. The rest of the code is the standard way to multiply two matrices, with each entry in `result`

calculated as the scalar product of a row of `X`

with a column of `Y`

. Note that there is no error checking in this code, not even that the number of columns of `X`

equals the number of rows of `Y`

.

Do you understand matrix multiplication and how Python stores a matrix in a list of lists, or do you need more explanation?

Source (Stackoverflow)