Non-zero element-wise comparison between two sparse matrices
Non-zero element-wise comparison between two sparse matrices
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.
fun: A function that receives 2 arguments and returns a scalar.
Returns
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.
Examples
# These two should yield the same results -----------------------------------# Creating two random matricesset.seed(89)A <- rgraph_ba(t =9, m =4)B <- rgraph_ba(t =9, m =4)A;B
# Comparingans0 <- matrix_compare(A,B,function(a,b)(a+b)/2)ans1 <- matrix(0, ncol=10, nrow=10)for(i in1:10)for(j in1:10) ans1[i,j]<- mean(c(A[i,j], B[i,j]))# Are these equal?all(ans0[]== ans1[])# Should yield TRUE
See Also
Other dyadic-level comparison functions: vertex_covariate_compare(), vertex_covariate_dist()