Let a = np.arange(1, 4)
.
To get the 2 dimensional multiplication table for a
, I do:
JavaScript
x
5
1
>>> a * a[:, None]
2
>>> array([[1, 2, 3],
3
[2, 4, 6],
4
[3, 6, 9]])
5
For 3 dimensions, I can do the following:
JavaScript
1
13
13
1
>>> a * a[:, None] * a[:, None, None]
2
>>> array([[[ 1, 2, 3],
3
[ 2, 4, 6],
4
[ 3, 6, 9]],
5
6
[[ 2, 4, 6],
7
[ 4, 8, 12],
8
[ 6, 12, 18]],
9
10
[[ 3, 6, 9],
11
[ 6, 12, 18],
12
[ 9, 18, 27]]])
13
How could I write a function that takes a numpy array a
and a number of dimensions n
as input and ouputs the n
dimensional multiplication table for a
?
Advertisement
Answer
This should do what you need:
JavaScript
1
9
1
import itertools
2
a = np.arange(1, 4)
3
n = 3
4
5
def f(x, y):
6
return np.expand_dims(x, len(x.shape))*y
7
8
l = list(itertools.accumulate(np.repeat(np.atleast_2d(a), n, axis=0), f))[-1]
9
Just change n
to be whatever dimension you need