Search code examples
c++matrixsparse-matrix

c++ construct matrix reading columns by columns


I want to implement the CSCmatrix (Compressed Sparse Coloumns) for doing this I need to read matrix given in this form :

{{1,2,3,4},{5,6,7,8}};

reading columns by columns! and not row by row (in this case i can use a simple costructor like in the follow )

template<typename T>
inline constexpr CSRmatrix<T>::CSRmatrix(std::initializer_list<std::initializer_list<T>>&& row ) noexcept
{
    this->rows = row.size();
    auto itr = *(row.begin());
    this->cols = itr.size();

    std::size_t i=0, j=0, w=0;  

    ia_.resize(rows+1);
    ia_[0] = 0;
    for(auto & r : row)
    {
        j=0 ; w =0 ;    
        for(auto & c : r)
        {
           if( c != 0.0 )
           {  
              a_.push_back(c);
             ja_.push_back(j);
             w++;
           }
           j++; 
        }
        i++;
        ia_[i] = ia_[i-1] + w ;
    }
}

this read row by row and stored the matrix in CSR format (compressed sparse row) could somebody help me about ? I have not idea ! thanks in advance

my data will be is stored in a single vector in this order {1,5,2,6,3,7,4,8}


Solution

  • If your data is declared as say vector<vector<T>> data, you can simply put data(v) in the initialization. But if you want to switch the rows and columns then use a temporary variable and switch the rows and columns.

    Edit, or use arr to put data in a single array

    This code assumes all rows in the initialization data are the same size

    template<typename T> class matrix
    {
    public:
        //std::vector<std::vector<T>> data;
        std::vector<T> arr;
        matrix(std::initializer_list<std::vector<T>> v) //: data(v)
        {
            if(!v.size()) return; //invalid input
            std::vector<std::vector<T>> temp(v);
            //test to make sure all row are the same size
            //use the size of row[0] for all other rows:
            for(size_t c = 0; c < temp[0].size(); c++)
            {
                for(size_t r = 0; r < temp.size(); r++)
                {
                    if(c < temp[r].size())
                        arr.push_back(temp[r][c]);
                    //else {invalid input}
                }
            }
            for(size_t c = 0; c < temp[0].size(); c++)
                for(size_t r = 0; r < temp.size(); r++)
                    arr.push_back(temp[r][c]);
        }
    };
    
    int main()
    {
        matrix<int> m = { { 1,2,3,4 },{ 5,6,7,8 } };
        for(auto e : m.arr) std::cout << e << ",";
        std::cout << "\n";
        return 0;
    }
    

    Output

    1,5,2,6,3,7,4,8,