Hadamard Product of Matrices
Definition
The Hadamard product of two matrices is defined as follows.
Description
The code for ’s is \odot
.
It is also commonly called the elementwise product. Unlike matrix multiplication, it is only defined for matrices of the same size and the commutative law applies.
Hadamard Product of Vectors
The Hadamard product of two vectors and is defined as follows.
The definition itself is a special case for matrices regarding the Hadamard product of matrices with . The following equation holds for diagonal matrices.
Hadamard Product of a Vector and a Matrix
The Hadamard product between a vector and a matrix is defined as follows.
Simply put, it takes the Hadamard product of the vector with each column of the matrix. The definition immediately gives the equation below.
Looking at the two definitions, one can see that for vector , defining itself as a matrix of is reasonable.
In Programming Languages
Such pointwise operations are implemented by adding a dot .
to the existing operation symbols. This notation is quite intuitive; for example, if multiplication is *
, then elementwise multiplication is .*
.
Julia
julia> A = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
1 2 3
4 5 6
julia> B = [2 2 2; 2 2 2]
2×3 Matrix{Int64}:
2 2 2
2 2 2
julia> A.*B
2×3 Matrix{Int64}:
2 4 6
8 10 12
MATLAB
>> A = [1 2 3; 4 5 6]
A =
1 2 3
4 5 6
>> B = [2 2 2; 2 2 2]
B =
2 2 2
2 2 2
>> A.*B
ans =
2 4 6
8 10 12
However, in the case of Python, since it is not a language for scientific computing like Julia or MATLAB, it is not implemented in the same way. The multiplication symbol *
stands for elementwise multiplication, and matrix multiplication is denoted by @
.
>>> import numpy
>>> A = np.array([[1, 2, 3], [4, 5, 6]])
>>> B = np.array([[2, 2, 2], [2, 2, 2]])
>>> A*B
array([[ 2, 4, 6],
[ 8, 10, 12]])
>>> import torch
>>> A = torch.tensor([[1, 2, 3],[4, 5, 6]])
>>> B = torch.tensor([[2, 2, 2],[2, 2, 2]])
>>> A*B
tensor([[ 2, 4, 6],
[ 8, 10, 12]])