Python Matrix Manipulation - Square Each Element
How do I take a matrix such as: matrix = [[2,0,2],[0,2,0],[2,0,2]] and transform it to [[4,0,4],[0,4,0],[4,0,4]] where all the elements in the list become squared? I'm trying to do
Solution 1:
Using list comprehension:
>>> lis = [[2,0,2],[0,2,0],[2,0,2]]
>>> [[y**2 for y in x] for x in lis]
[[4, 0, 4], [0, 4, 0], [4, 0, 4]]
Solution 2:
List comprehensions can be nested:
sqd = [[elem*elem for elem ininner] forinnerinouter]
In this case outer
would be your matrix matrix
>>>> matrix = [[2,0,2],[0,2,0],[2,0,2]]
>>>> sqd = [[elem*elem for elem in inner] for inner in matrix]
>>>> sqd
[[4, 0, 4], [0, 4, 0], [4, 0, 4]]
Solution 3:
Use numpy:
import numpy as np
matrix = [[2,0,2],[0,2,0],[2,0,2]]
np_matrix = np.array(matrix)
np_matrix**2
A list comprehension could look like this
matrix2 = [
[e*e for e in l]
for l in matrix
]
Solution 4:
If you mean by
matrix = [[2,0,2],[0,2,0],[2,0,2]]
a list of lists, then do the following
import numpy as np
np.square(matrix)
This gives you output as follows:
array([[4, 0, 4],
[0, 4, 0],
[4, 0, 4]], dtype=int32)
However, if you really mean it to be a matrix, you have to create a matrix first as follows:
X = np.matrix('2 0 2; 0 2 0; 2 0 2')
and then do the same as above, i.e.,
np.square(X)
This gives you the desired output as follows:
[[4 0 4]
[0 4 0]
[4 0 4]]
Post a Comment for "Python Matrix Manipulation - Square Each Element"