Skip to content
Advertisement

Broadcasting over two arrays with different shapes (Numpy-Python)

Suppose I have the following arrays:

JavaScript

So an array with shape (5, 5)

Now I have a second array, which is a slice of the first:

JavaScript

An array with shape (2, 5).

Now I want to subtract every vector of the first array by the vectors of the second array subsequently(excluding- in the first array- the vector of the second array I’m using to subtract), element-wise. I want to this for every vector of the second array.

So I want to have as an output:

JavaScript

So this is an array with shape (2, 4, 5)

How do we do this with broadcasting?

Advertisement

Answer

Does this code do what you meant you needed done?
You are welcomed to test it on your test case and update me if you need more help.

JavaScript

EDIT: here’s a more efficient method:

JavaScript

output:

JavaScript

EDIT 2: I subtracted the arrays in the wrong order (the whole array from the slice instead of the other way around). So here’s a fix and this time I’m using your example:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement