python - 具有特征的稀疏随机矩阵

标签 python c++ sparse-matrix eigen

是否可以使用 C++ Eigen 库制作一个(稀疏)矩阵,类似于我需要翻译的这个优雅的 python 代码?

(np.random.rand(100,100)  < 0.1) * np.random.rand(100,100)

例如用一定比例的随机值填充的矩阵。

最佳答案

直接改编自Eigen Documentation , 而不是那么简洁:

std::default_random_engine gen;
std::uniform_real_distribution<double> dist(0.0,1.0);

int rows=100;
int cols=100;

std::vector<Eigen::Triplet<double> > tripletList;
for(int i=0;i<rows;++i)
    for(int j=0;j<cols;++j)
    {
       auto v_ij=dist(gen);                         //generate random number
       if(v_ij < 0.1)
       {
           tripletList.push_back(T(i,j,v_ij));      //if larger than treshold, insert it
       }
    }
SparseMatrixType mat(rows,cols);
mat.setFromTriplets(tripletList.begin(), tripletList.end());   //create the matrix

这需要 C++11 且未经测试。

关于python - 具有特征的稀疏随机矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30741884/

相关文章:

python - 尝试在 python 中追加 jar 文件失败

python - 为什么在加载模块时使用 Paramiko 会挂起?

c++ - 为什么visual studio会忽略项目文件中指定的tlb文件名

python - 如何计算非常大的 scipy 稀疏矩阵之间的点积

python - 稀疏矩阵 : how to get nonzero indices for each row

Python - flask.request.files.stream 应该是什么类型?

python - 如何将一个类的功能分离到多个文件中?

c++如何在cmd上显示运行时间??作为运行时钟改变需要系统 ("clear")?

c++ - 为什么未分配的内存标记为 0xCC?

c - SpMV 算法的大小与时间图中的不规则时间跳跃