Hadamard product {tensorEVD} | R Documentation |
Hadamard product
Description
Computes the Hadamard product between two matrices
Usage
Hadamard(A, B, rowsA, rowsB,
colsA = NULL, colsB = NULL,
make.dimnames = FALSE,
drop = TRUE, inplace = FALSE)
Arguments
A |
(numeric) Left numeric matrix |
B |
(numeric) Right numeric matrix |
rowsA |
(integer/character) Vector of length m with either indices or row names mapping from rows of |
rowsB |
(integer/character) Vector of length m with either indices or row names mapping from rows of |
colsA |
(integer/character) (Optional) Similar to |
colsB |
(integer/character) (Optional) Similar to |
drop |
Either |
make.dimnames |
|
inplace |
|
Details
Computes the m × n Hadamard product (aka element-wise or entry-wise product) matrix between matrices A0 = R1 A C'1 and B0 = R2 B C'2,
(R1 A C'1) ⊙ (R2 B C'2)
where
R1 and
R2 are incidence matrices for rows that can be formed by integer vectors
rowsA
and rowsB
of length m, respectively, and
C1 and
C2 are incidence matrices for columns that can be formed by integer vectors
colsA
and colsB
of length n, respectively.
Matrices A0 and
B0 can be obtained by matrix indexing as A[rowsA,colsA]
and B[rowsB,colsB]
, respectively. Therefore, the Hadamard product can be obtained directly as
A[rowsA,colsA]*B[rowsB,colsB]
The function computes the Hadamard product directly from A and B without forming A0 or B0 matrices.
Value
Returns a matrix containing the Hadamard product.
Examples
require(tensorEVD)
# ==============================================
# Example 1. Indexing using integers
# ==============================================
# Generate rectangular matrices A (nrowA x ncolA) and B (nrowB x ncolB)
nA = c(10,15)
nB = c(12,8)
A = matrix(rnorm(nA[1]*nA[2]), nrow=nA[1])
B = matrix(rnorm(nB[1]*nB[2]), nrow=nB[1])
# Define size of the Hadamard n1 x n2
n1 = 1000
n2 = 500
rowsA = sample(seq(nA[1]), n1, replace=TRUE)
rowsB = sample(seq(nB[1]), n1, replace=TRUE)
colsA = sample(seq(nA[2]), n2, replace=TRUE)
colsB = sample(seq(nB[2]), n2, replace=TRUE)
# Direct hadamard product
K1 = A[rowsA,colsA]*B[rowsB,colsB]
# Using 'Hadamard' function
K2 = Hadamard(A, B, rowsA, rowsB, colsA, colsB)
all.equal(K1,K2) # They should be equal
# ==============================================
# Example 2. Indexing using row/column names
# ==============================================
# Generate squared symmetric matrices A and B
nA = 20
nB = 15
A = tcrossprod(matrix(rnorm(nA*nA), nrow=nA, dimnames=list(paste0("id",seq(nA)))))
B = tcrossprod(matrix(rnorm(nB*nB), nrow=nB, dimnames=list(paste0("id",seq(nB)))))
# Define size of the Hadamard n x n
n = 1000
IDA = sample(rownames(A), n, replace=TRUE)
IDB = sample(rownames(B), n, replace=TRUE)
# Direct hadamard product
K1 = A[IDA,IDA]*B[IDB,IDB]
dimnames(K1) = list(paste0(IDA,":",IDB), paste0(IDA,":",IDB))
# Using 'Hadamard' function
K2 = Hadamard(A, B, IDA, IDB, make.dimnames=TRUE)
all.equal(K1,K2) # They should be equal