# How to differentiate a matrix of functions

I want a simple elementwise derivative of a matrix. Could not find anything precoded, which was surprising. I tried a few versions, the following is probably the simplest.

import numpy as np
from sympy import *
import sympy as sp

t = symbols(‘t’)

a = np.array([[t**2 + 1, sp.exp(2*t)], [sin(t), 45]])

for row in a:
for element in row:
a[row][element] = diff(a[row][element],t)

print(a)

and the error section that shows in Jupyter:
IndexError Traceback (most recent call last)
Input In [25], in <cell line: 9>()
9 for row in a:
10 for element in row:
—> 11 a[row][element] = diff(a[row][element],t)
13 print(a)

IndexError: arrays used as indices must be of integer (or boolean) type

When you index an array, the indices have to be the index number.

But when you iterate over the rows, you get the entire row as an array, not the indices. So this:

``````for row in a:
``````

sets row to a full row, and then `a[row]` fails.

Likewise when you iterate over the row, to get the elements, you would then attempt to index using a symbolic expression (the derivative).

I’m not a numpy expert, but I think what you need is:

``````
# Untested.
for row_number, row in enumerate(a):
for column_number, element in enumerate(row):
a[row_number][column_number] = diff(element, t)
``````

although there is probably a better way. Also that assumes that the array is two dimensional, and will fail on 1 or 3+ dimensional arrays.