Learn R Programming

netdiffuseR (version 1.22.6)

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)

Value

An object of class dgCMatrix of size n*m.

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.

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
# 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

Run the code above in your browser using DataLab