In python, suppose I have a square numpy
matrix X, of size n x n and I have a numpy
vector a of size n.
Very simply, I want to perform a broadcasting subtraction of X - a, but I want to be able to specify along which dimension, so that I can specify for the subtraction to be either along axis 0 or axis 1.
How can I specify the axis?
Let's generate arrays with random elems
Inputs :
I. Subtraction along
axis=1
Let's do the subtraction along
axis=1
, i.e. we want to subtracta
from the first row ofX
, the second row ofX
and so on. For ease of inspecting correctness, let's just use the first row ofX
:Going deeper there, what's happening there is :
So, we are matching the second axis of
X
with the first axis ofa
. Since,X
is2D
anda
is1D
, both are already aligned :So, we simply do
X-a
to get all subtractions :And, finally see if we have
X[0] - a
obtained earlier is here.Important Note : Thing to be noted here is that
a
elems would be along one axis and along that subtraction would be done and the broadcasting would happen along the other axis. So, in this case, even though subtraction is happening alongaxis=1
, elems ofa
would be broadcasted along theaxis=0
.II. Subtraction along
axis=0
Similarly, let's do the subtraction along
axis=0
, i.e. we want to subtracta
from the first col ofX
, the second col ofX
and so on. For ease of inspecting correctness, let's just use the first col ofX
:Going deeper there, what's happening there is :
So, we are matching the first axis of
X
with the first axis ofa
. Since,X
is2D
anda
is1D
, we need to extenda
to2D
and keep all elems along its first axis witha[:,None]
:So, we do
X-a[:,None]
to get all subtractions :And, finally see if we have
X[:,0] - a
obtained earlier is here.Start with 2 dimensions that are different (in label at least)
X
shape(n,m)
a
shape(n,)
b
shape(m,)
The ways to combine these are:
The basic point is that when the number dimensions differ,
numpy
can add new dimensions at the start, but you have to be explicit about adding new dimensions at the end.Or to combine 2 1d arrays in a outer product (difference):
Without the these rules,
a-b
could result in a(n,m)
or(m,n)
or something else.And with 2 matching length arrays:
or
=============
To write a function that would take an
axis
parameter, you could usenp.expand_dims
:to be used as: