How to multiply a given row `i` or column` j` with a scalar?

import numpy as np M = np.matrix([ [-1,-2,-3], [-4,-5,-6] ]) print(M) 
  • How to multiply a given row i or column j with a scalar?
  • How to access the specified column or row as a list?
  • How to set a given column or row given a list (of suitable length)?
+4
source share
3 answers

You can use slicing to do the following:

 >>> M = np.matrix([ ... [-1,-2,-3], ... [-4,-5,-6] ... ]) >>> M[1,:] *= 2 # multiply all elements in second row by 2 >>> M matrix([[ -1, -2, -3], [ -8, -10, -12]]) >>> M[:,1] *= 2 # multiply all elements in second column by 2 >>> M matrix([[ -1, -4, -3], [ -8, -20, -12]]) 

To assign a given column or row to a list:

 >>> M[:,1] = [[0], [0]] # note the nested lists to reassign column >>> M matrix([[ -1, 0, -3], [ -8, 0, -12]]) >>> M[1,:] = [2, 2, 2] # flat list to reassign row >>> M matrix([[-1, 0, -3], [ 2, 2, 2]]) 
+6
source

To multiply a specific column:

 M[:,colnumber] *= scalar 

Or a line:

 M[rownumber,:] *= scalar 

And, of course, accessing them as iterable is the same thing:

 col_1 = M[:,1] 

Although this gives you a new matrix, not a list . Although, frankly, I can not fully understand all these operations with matrix objects. And this is not like operations like matrix . Is there a reason why you use matrix instead of array objects? If you want to multiply the matrix, you can always use np.dot(array_mat1, array_mat2)

+6
source

Using Python 2.7

1) You can multiply a row or column by some scalar s as follows:

 M[i, :] *= s M[:, j] *= s 

2) You can access a row or column, for example:

 M[i, :] M[:, j] 

3) You can set a row or column to list l as follows:

 M[i, :] = l M[:, j] = l 

Note that in the latter case, your list (if you set the column) must be a list in the list (i.e. the external list acts like a row, the internal lists act like columns).

0
source

All Articles