如何在犰狳中按元素划分2个稀疏矩阵?

问题描述

我是 C++ 新手,但我正在使用 R 和 RcppArmadillo,我的目标是按元素划分 2 个稀疏矩阵。我在 Armadillo 的文档中读到操作符是 /,但是当我使用 sourceCpp 获取我的代码时,我收到了这个错误:

'operator/' 不匹配(操作数类型是 'arma::sp_mat' {aka 'arma::SpMat'} 和 'arma::sp_mat' {aka 'arma::SpMat'})

我写了一个小代码示例。请注意,当我从脚本中删除除法函数时,乘法函数可以正常工作。

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>

using namespace Rcpp;

//' Sparse Matrix element-wise multiplication
//'
//' @param X sp_mat 
// [[Rcpp::export]]
arma::sp_mat sp_mat_mul(arma::sp_mat X){
  
  arma::sp_mat Y = X % X;
  return Y;
  
}


//' Sparse Matrix element-wise division
//'
//' @param X sp_mat 
// [[Rcpp::export]]
arma::sp_mat sp_mat_div(arma::sp_mat X){
  
  arma::sp_mat Y = X / X;
  return Y;
  
}

感谢您抽出宝贵时间,我真的很感激!

解决方法

使用transform/foreach计算逆然后相乘。

//' Sparse Matrix element-wise division
//'
//' @param X sp_mat 
// [[Rcpp::export]]
arma::sp_mat sp_mat_div(arma::sp_mat X){
  arma::sp_mat x_inverse(X);
  x_inverse.transform([](double val) {return (1.0/val);});
  arma::sp_mat Y = X % x_inverse;
  return Y;
}

R:

i <- c(1,3:8)
j <- c(2,9,6:10)
x <- 7 * (1:7)
A <- sparseMatrix(i,j,x = x)

sp_mat_div(A)
[1,] . 1 . . . . . . . .
[2,] . . . . . . . . . .
[3,] . . . . . . . . 1 .
[4,] . . . . . 1 . . . .
[5,] . . . . . . 1 . . .
[6,] . . . . . . . 1 . .
[7,] . . . . . . . . 1 .
[8,] . . . . . . . . . 1

顺便说一句,你确定这个操作有意义吗?

你忽略了矩阵中的所有零(因为它是稀疏矩阵),如果这是一个非稀疏矩阵,你会被零除很多。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...