'how to access a matrix and increase specific column?

For example, I have this matrix, and I need to access the second column and increase it by 2:

 m = [[0. 0. 0. 0.]
      [0. 0. 0. 0.]
      [0. 0. 0. 0.]
      [0. 0. 0. 0.]]


Solution 1:[1]

You can do that just by accessing the 2nd column and incrementing the value. You can do that by doing this : m[:, 1] = m[:, 1] + 2

It means that you are ignoring all the rows and specifying the columns. Here, 1 refers to the 2nd column.

You can do this by using numpy library which allows you to easily do such thing.

Import numpy as import numpy as np

Convert the 2d list into numpy array

m = np.array([
 [0., 0., 0., 0.], 
 [0., 0., 0., 0.], 
 [0., 0., 0., 0.], 
 [0., 0., 0., 0.]
])

Now apply the conditioning

m[:, 1] = m[:, 1] + 2

Print the output.

print("M: ", m)

Combined Code:

import numpy as np
m = np.array([
 [0., 0., 0., 0.], 
 [0., 0., 0., 0.], 
 [0., 0., 0., 0.], 
 [0., 0., 0., 0.]
 ])

m[:, 1] = m[:, 1] + 2
print("M: ", m)

Output

Solution 2:[2]

So, you need to increase the second element of each row by 2. You could achieve this by a for loop.

for row in m:
    row[1] += 2

Solution 3:[3]

You could convert the matrix into a numpy array. Just in case you're looking at exploiting the optimisations that this library offers

import numpy as np
m = np.array([
    [0., 0., 0., 0.], 
    [0., 0., 0., 0.], 
    [0., 0., 0., 0.], 
    [0., 0., 0., 0.]
])

m[:, 1] += 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sdq
Solution 3 helloworld