Learn R Programming

netdiffuseR (version 1.20.2)

matrix_compare: Non-zero element-wise comparison between two sparse matrices

Description

Taking advantage of matrix sparseness, the function only evaluates fun between pairs of elements of A and B where either A or B have non-zero values. This can be helpful to implement other binary operators between sparse matrices that may not be implemented in the Matrix package.

Usage

matrix_compare(A, B, fun)

compare_matrix(A, B, fun)

Arguments

A

A matrix of size n*m of class dgCMatrix.

B

A matrix of size n*m of class dgCMatrix.

fun

A function that receives 2 arguments and returns a scalar.

Value

An object of class dgCMatrix of size n*m.

Details

Instead of comparing element by element, the function loops through each matrix non-zero elements to make the comparisons, which in the case of sparse matrices can be more efficient (faster). Algorithmically it can be described as follows:

# Matrix initialization
init ans[n,m];

# Looping through non-zero elements of A for e_A in E_A: ans[e_A] = fun(A[e_A], B[e_A])

# Looping through non-zero elements of B and applying the function # in e_B only if it was not applied while looping in E_A. for e_B in E_B: if (ans[e_B] == Empty) ans[e_B] = fun(A[e_B], B[e_B])

compare_matrix is just an alias for matrix_compare.

See Also

Other dyadic-level comparison functions: vertex_covariate_compare, vertex_covariate_dist

Examples

Run this code
# NOT RUN {
# These two should yield the same results -----------------------------------

# Creating two random matrices
set.seed(89)
A <- rgraph_ba(t = 9, m = 4)
B <- rgraph_ba(t = 9, m = 4)
A;B

# Comparing
ans0 <- matrix_compare(A,B, function(a,b) (a+b)/2)

ans1 <- matrix(0, ncol=10, nrow=10)
for (i in 1:10)
  for (j in 1:10)
    ans1[i,j] <- mean(c(A[i,j], B[i,j]))

# Are these equal?
all(ans0[] == ans1[]) # Should yield TRUE

# More elaborated example (speed) -------------------------------------------
# }
# NOT RUN {
set.seed(123123123)
A <- rgraph_ba(t = 5e3, m = 2)
B <- rgraph_ba(t = 5e3, m = 2)

Am <- as.matrix(A)
Bm <- as.matrix(B)

compfun <- function(a,b)
  ifelse(a > b, a, b)

microbenchmark::microbenchmark(
  diffnet = matrix_compare(A, B, compfun),
  R       = matrix(ifelse(Am > Bm, Am, Bm), ncol=ncol(Am)),
  times   = 10
)
# Unit: milliseconds
#    expr       min        lq      mean    median        uq      max neval
# diffnet  352.7989  355.0193  583.5366  357.7138  364.7604 2493.914    10
#       R 1648.9607 1744.6762 2491.2435 1947.4344 2729.1274 6260.011    10

# }

Run the code above in your browser using DataLab