簡體   English   中英

使用密集和稀疏矩陣

[英]Working with both dense and sparse matrices

我正在編寫一個C ++函數,它在矩陣上運行,作為參數傳遞,並希望代碼能夠處理不同類型的矩陣(例如Boost稀疏矩陣,std :: vector的std :: vectors)。 我目前的方法是為不同類型的基本矩陣操作定義重載方法,為不同類型的矩陣提供統一的接口,並將我的函數定義為僅使用這些重載方法的模板函數

#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <iostream>

typedef std::vector<double> vec;
typedef std::vector<vec> mat;
typedef boost::numeric::ublas::compressed_matrix<double, boost::numeric::ublas::row_major> spmat;

namespace matrix
{
    inline void set(spmat & input, u_int i, u_int j, double val)
    {
        input(i, j) = val;
    }

    inline void set(mat & input, u_int i, u_int j, double val)
    {
        input[i][j] = val;
    }

    inline u_int size1(const mat & input)
    {
        return input.size();
    }

    inline u_int size2(const mat & input)
    {
        return input[0].size();
    }

    inline u_int size1(const spmat & input)
    {
        return input.size1();
    }

    inline u_int size2(const spmat & input)
    {
        return input.size2();
    }

    inline double get(const spmat & input, u_int i, u_int j)
    {
        return input(i, j);
    }

    inline double get(const mat & input, u_int i, u_int j)
    {
        return input[i][j];
    }
}

對於簡單的任務,這種方法似乎有效。 然而,目前,我正在嘗試編寫一個需要迭代所有條目的函數,在密集矩陣的情況下,或者在稀疏矩陣的情況下只迭代非零條目。 我知道如何為每個案例單獨執行此操作,但希望只有一個實現在兩種情況下都有效。 實現這一目標的標准方法是什么?

我曾經也有過一樣的問題。 由於我懶得編寫迭代器(很快會遇到限制),我決定使用lambda方法,為每個元素定義一個lambda的特殊函數:

template<class Func>
void forMatrixEntries(const VecOfVecMatrix& mat, Func&& func)
{
    for (auto& row : mat.getData())
        for (auto& elem : row)
            func(elem); // You could track and pass the indices if you want.
}

template<class Func>
void forMatrixEntries(const CompressedSparseMatrix& mat, Func&& func)
{
    for (auto& elem : mat.getElements())
        func(elem); // You could track and pass the indices if you want.
}

(這些也可以是成員函數,因此他們可以更輕松地訪問內部 - 您的選擇)。 然后,您可以以統一的方式使用它們:

template<class Mat>
void scale(const Mat& mat, double factor)
{
    forMatrixEntries(mat, [factor](double& elem) {
        elem *= factor;
    });
}

唯一的缺點是矩陣專用函數當然需要在標題中(因為模板)。 但我認為這種方法不僅優雅而且非常具有表現力(你可以給“迭代矩陣條目”而不是復雜的循環語法,但循環體保持不變)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM