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.

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

# 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
#> 10 x 10 sparse Matrix of class "dgCMatrix"
#>   [[ suppressing 10 column names ‘1’, ‘2’, ‘3’ ... ]]
#>                       
#> 1  1 . . . . . . . . .
#> 2  1 . . . . . . . . .
#> 3  . . 2 . . . . . . .
#> 4  . . 1 2 . . . . . .
#> 5  1 2 . . 1 . . . . .
#> 6  1 . 2 . 1 . . . . .
#> 7  2 1 . . . 1 . . . .
#> 8  1 . 1 1 1 . . . . .
#> 9  1 . 1 1 1 . . . . .
#> 10 . 1 . 1 . . . 2 . .
#> 10 x 10 sparse Matrix of class "dgCMatrix"
#>   [[ suppressing 10 column names ‘1’, ‘2’, ‘3’ ... ]]
#>                       
#> 1  1 . . . . . . . . .
#> 2  . 1 . . . . . . . .
#> 3  . 2 . . . . . . . .
#> 4  2 . 1 . . . . . . .
#> 5  1 1 . 1 1 . . . . .
#> 6  . 1 1 . 2 . . . . .
#> 7  . . 2 1 1 . . . . .
#> 8  1 1 1 . . 1 . . . .
#> 9  2 . . . 1 1 . . . .
#> 10 . 1 . . . . 1 . 1 1

# 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
#> [1] TRUE