2

Is there a way to do column-wise (or row-wise) operations on matrices in sympy? For example, dividing each column of a matrix by its norm, or multiplying each row of a matrix by its norm?

Hatshepsut
  • 5,962
  • 8
  • 44
  • 80
  • Isn't multiplying each column the same as multiplying the whole matrix? – asmeurer Sep 20 '15 at 18:03
  • Thanks for responding! For multiplication I could just multiply AD with a diagonal matrix D containing the values to multiply by (e.g. the norm of each column). I was hoping for a solution to doing arbitrary functions to the columns of a matrix. One solution is simply to loop through the columns, applying the function. But there's no matrix-comprehension-by-columns feature, like how list and dictionary comprehensions work? – Hatshepsut Sep 20 '15 at 18:43

1 Answers1

2

You can use row_op and col_op. From the documentation for row_op:

row_op(i, f) method of sympy.matrices.dense.MutableDenseMatrix instance
    In-place operation on row ``i`` using two-arg functor whose args are
    interpreted as ``(self[i, j], j)``.

These methods act in-place:

>>> a = Matrix([[1, 2], [3, 4]])
>>> a.row_op(1, lambda i, j: i*2)
>>> a
Matrix([
[1, 2],
[6, 8]])
asmeurer
  • 86,894
  • 26
  • 169
  • 240