ricardo - 2 months ago 6x

Python Question

**hello all,** need to define a function that can be divided term by term matrix or in the worst cases, between arrays of lists so you get the result in a third matrix,

thanks for any response

Answer

Unless I'm misunderstanding, this is where `numpy`

can be put to good use:

```
>>> from numpy import *
>>> a = array([[1,2,3],[4,5,6],[7,8,9]])
>>> b = array([[0.5] * 3, [0.5] * 3, [0.5] * 3])
>>> a / b
array([[ 2., 4., 6.],
[ 8., 10., 12.],
[ 14., 16., 18.]])
```

This works for multiplication too. And indeed, as noted by Mark, scalar division (and multiplication) is also possible:

```
>>> a / 10.0
array([[ 0.1, 0.2, 0.3],
[ 0.4, 0.5, 0.6],
[ 0.7, 0.8, 0.9]])
>>> a * 10
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
```

**Edit**: to be complete, for lists of lists you could do the following:

```
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> b = [[0.5] * 3, [0.5] * 3, [0.5] * 3]
>>> def mat_div(a, b):
... return [[n / d for n, d in zip(ra, rb)] for ra, rb in zip(a, b)]
...
>>> mat_div(a, b)
[[2.0, 4.0, 6.0], [8.0, 10.0, 12.0], [14.0, 16.0, 18.0]]
```

Source (Stackoverflow)

Comments