Reputation: 1082
np_mat = np.array([[1, 2], [3, 4], [5, 6]])
np_mat + np.array([10, 10])
I am confused what the difference between np.array([10, 10]) and np.array([[10, 10]]) is. In school I learnt that only matrices with the same dimensions can be added. When I use the shape method on np.array([10, 10]) it gives me (2,)...what does that mean? How is it possible to add np_mat and np.array([10, 10])? The dimensions don't look the same to me. What do I not understand?
Upvotes: 1
Views: 2087
Reputation: 881
You cannot add two arrays of different sizes.
But those two both have first dimension, length, equal to 2. (that is len(a) == len(b)
)
Shape (2,)
means that the array is one-dimensional and the first dimension is of size 2.
np.array([[1, 2], [3, 4], [5, 6]])
has shape (3, 2)
which means two-dimensional (3x2).
But you can add them since they are of different dimensions, and numpy coerces a number to an arbitrary array full of this same number. This is called broadcasting in numpy.
I.e. your code gets equivalent results to:
np_mat = np.array([[1, 2], [3, 4], [5, 6]])
np_mat + 10
Or to:
np_mat = np.array([[1, 2], [3, 4], [5, 6]])
np_mat + np.array([[10, 10], [10, 10], [10, 10]])
Upvotes: 1
Reputation: 1793
It looks like numpy is bending the rules of mathematics here. Indeed, it sums the second matrix [10, 10]
with each element of the first [[1, 2], [3, 4], [5, 6]]
.
This is called https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html. The shape of [10, 10]
is (2, )
(that is, mathematically, 2
) and that of [[1, 2], [3, 4], [5, 6]]
is (3, 2)
(that is, mathematically, 3 x 2
). Therefore, from general broadcasting rules, you should get a result of shape (3, 2)
(that is, mathematically, 3 x 2
).
I am confused what the difference between np.array([10, 10]) and np.array([[10, 10]]) is.
The first is an array. The second is an array of arrays (in memory, it is in fact one single array, but this is not relevant here). You could think of the first as a column vector (a matrix of size 2 x 1
) and the second as a line vector (a matrix of size 1 x 2
). However, be warned that the distinction between line and column vectors is irrelevant in mathematics until you start interpreting vectors as matrices.
Upvotes: 1