2

Suppose I have four matrices, a, b, c, and d.

In Python (with numpy), I need to do result = np.matmul(np.matmul(np.matmul(a,b),c),d) to multiply them.

In MATLAB/GNU Octave, I can multiply them in a much simpler manner, result = a*b*c*d.

Is there any way to multiply matrices in Python, so that I would not have to repeatedly write np.matmul avoid nested brackets?

  • More generally you can use [`functools.reduce`](https://docs.python.org/3/library/functools.html#functools.reduce) – Steve Feb 02 '22 at 12:44
  • I was using lists to implement matrices, they can be converted to numpy.matrix form with `aNew = np.asmatrix(a)`, and can be multiplied with `aNew@bNew@cNew@dNew` – Archisman Panigrahi Feb 02 '22 at 12:46

1 Answers1

5

Use the @ operator. result = a@b@c@d.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • I did `>>> a = [[1,2],[3,4]]`, followed by `>>> a@a`, and got `Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for @: 'list' and 'list' ` – Archisman Panigrahi Feb 02 '22 at 12:35
  • 1
    @ArchismanPanigrahi Why are you trying this with lists? You tagged `numpy`. Use `numpy.array` or `numpy.matrix`. – timgeb Feb 02 '22 at 12:35
  • @ArchismanPanigrahi you'll want to change them into arrays where you define them with [`np.array()`](https://numpy.org/doc/stable/reference/generated/numpy.array.html) – Steve Feb 02 '22 at 12:37
  • 1
    I had implemented the matrices in a list, and used numpy to multiply them. Did not know about numpy arrays. Thanks. – Archisman Panigrahi Feb 02 '22 at 12:38