Residualizes the rows of `matrix_to_residualize` with respect to the row space of `subspace_basis_matrix`. This is equivalent to projecting each column of `t(matrix_to_residualize)` onto the column space of `t(subspace_basis_matrix)` and taking the residuals. Sparse inputs are processed with `Matrix` routines and the result is returned as a dense matrix.
Arguments
- matrix_to_residualize
A numeric matrix (e.g., `C x k`) whose rows are to be residualized. Sparse `Matrix` inputs are handled without full densification. A warning is issued if the matrix is very large (`C*k > 1e7`).
- subspace_basis_matrix
A numeric matrix (e.g., `m x k`) whose rows span the subspace to project out. Sparse matrices are accepted and processed with `Matrix` linear algebra.
Value
A numeric matrix with the same dimensions as `matrix_to_residualize`, containing the residualized rows.
Examples
# Z_i: 3 conditions, 5-dimensional spectral space (3x5)
Z_i <- matrix(rnorm(15), nrow = 3, ncol = 5)
# A_parc_i: 2 anchor parcels, 5-dimensional spectral space (2x5)
A_parc_i <- matrix(rnorm(10), nrow = 2, ncol = 5)
Z_i_res <- residualize_matrix_on_subspace(Z_i, A_parc_i)
print(dim(Z_i_res))
#> [1] 3 5
if (nrow(A_parc_i) > 0 && ncol(A_parc_i) > 0 && qr(t(A_parc_i))$rank > 0) {
# Test orthogonality: Z_i_res %*% t(A_parc_i) should be near zero
print(round(Z_i_res %*% t(A_parc_i), 10))
}
#> [,1] [,2]
#> [1,] 0 0
#> [2,] 0 0
#> [3,] 0 0
# Sparse example
Z_sp <- Matrix::rsparsematrix(3, 5, 0.3)
A_sp <- Matrix::rsparsematrix(2, 5, 0.3)
residualize_matrix_on_subspace(Z_sp, A_sp)
#> Error in residualize_matrix_on_subspace(Z_sp, A_sp): matrix_to_residualize must be a numeric matrix or Matrix object.