kabi994
kabi994

Reputation: 3

Numpy - How generate the following n-dimensional matrix

Let's consider two matrix "A,B" $(2 \times 2)$, how can I get the result "C" below, using numpy?

Here the code for the matrix A and B:

import numpy as np

A = np.array([
    [1, 1],
    [2, 2],
])

B = np.array([
    [0.5, 0.3],
    [0.1, 0.6],
])

# My desired output: 
C = [
    [
        [1*0.5, 1*0.3],
        [1*0.1, 1*0.6],
    ],
    [
        [2*0.5, 2*0.3],
        [2*0.1, 2*0.6],
    ],
]

thanks in advance!!

Upvotes: 0

Views: 43

Answers (1)

Ari Cooper-Davis
Ari Cooper-Davis

Reputation: 3485

You can add a new axis to your first array in order to multiply into that axis:

C = A[:, np.newaxis]*B

Upvotes: 1

Related Questions