简体   繁体   English

使用对的矩阵乘法

[英]Matrix multiplication using pairs

I am looking into alternate ways to do a Matrix Multiplication. 我正在寻找其他方法来进行矩阵乘法。 Instead of storing my matrix as a two-dimensional array, I am using a vector such as 我没有将我的矩阵存储为二维数组,而是使用了一个向量

vector<pair<pair<int,int >,int > > 

to store my matrix. 存储我的矩阵。 The pair within my pair (pair) stores my indices (i,j) and the other int stores the value for the given (i,j) pair. 我的对(对)中的对存储我的索引(i,j),而另一个int存储给定(i,j)对的值。 I thought I might have some luck implementing my sparse array this way. 我想我可能会以这种方式实现我的稀疏数组。

The problem is when I try to multiply this matrix with itself. 问题是当我尝试将此矩阵与其自身相乘时。

If this was a 2-d array implementation, I would have multiplied the matrix as follows: 如果这是一个二维数组实现,我会将矩阵乘以如下:

   for(i=0; i<row1; i++)
    {
        for(j=0; j<col1; j++)
        {
          C[i][j] = 0;
         for(k=0; k<col2; k++) 
           C[i][j] += A[i][j] * A[j][k];
      }
    }

Can somebody point out a way to achieve the same result using my vector of 'pair of pairs'? 有人能指出使用我的'对配对'矢量来达到相同结果的方法吗?

Thanks 谢谢

So far you can store one value at one location. 到目前为止,您可以在一个位置存储一个值。 If you want to store several nonzero entries in the matrix, you will need more pairs of pairs in a larger structure. 如果要在矩阵中存储多个非零项,则需要在更大的结构中使用更多对。

map<pair<int, int>, int> would be the next logical step. map<pair<int, int>, int>将是下一个逻辑步骤。 Now you can iterate over rows because the first coordinate is more significant in the map 's sorting order. 现在您可以遍历行,因为第first坐标在map的排序顺序中更为重要。

To iterate over columns, reverse that precedence: 要迭代列,请反转该优先级:

typedef pair<int, int> mx_coord;
struct reverse_compare {
    bool operator() (mx_coord const &l, mx_coord const &r) const
        { return l.second < r.second? true :
                 r.second < l.second? false : l.first < r.first; }
};

typedef map< mx_coord, int > matrix;
typedef map< mx_coord, int, reverse_compare > matrix_transpose;

To multiply A by B, transpose B and iterate over A and B, multiplying any elements whose less-significant coordinates match, as the ordering naturally lets you go line-by-line and column-by-column. 要将A乘以B,转置B并迭代A和B,将任意不太重要的坐标匹配的元素相乘,因为排序自然会让您逐行和逐列。

To transpose B: 要转置B:

matrix_transpose b_t( b.begin(), b.end() ); // complexity: n log n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM