0

I have an array A which has the shape (2, n) and second array B with the shape (n, 2) and I want to create an array C with the shape (n, 2, 2) by multiplying axis=0 of the first array A and axis=1 of the second array B to receive 10 "arrays" of the shape (2, 2) which are stored in the array C

I dont know how to do this... hope someone can help, thanks in advance!

Here some test data with n=10:

A = [array([1, 2, 3, 4, 4, 4, 4, 4, 4, 2]), array([2, 3, 2, 4, 3, 6, 8, 5, 2, 1])]
B = [array([1, 2]), array([3, 2]), array([1, 1]), array([2, 2]), array([6, 1]), array([4, 5]), array([1, 2]), array([1, 2]), array([1, 2]), array([1, 2])]

1 Answer 1

1

You can use moveaxis to change the array shapes to line up, then insert additional axes as necessary:

C = np.moveaxis(A, 1, 0)[..., None] * B[:, None, ...]

Another way would be to apply it after the multiplication, but that would run the risk of creating a non-contiguous memory layout, and is therefore generally less desirable:

C = np.moveaxis(A[..., None] * B[None, ...], 1, 0)

Similar results can be achieved with transpose and swapaxes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.