乘法矩阵(c++)的算法有问题

Trouble with algorithm for multiplying matrix (c++)

本文关键字:算法 有问题 c++      更新时间:2023-10-16

嗨,我正在帮我的一个朋友写一个程序,可以在不扩展矩阵的情况下将两个上三角矩阵相乘。当我说不展开矩阵时,我的意思是不用零填充上三角矩阵的下部(目标是节省空间)。我正在从一个文件中读取矩阵,该文件只包含矩阵的上三角值,省略了下部分。

我试图完成的是编写一个函数,在给定一个数组和一对索引的情况下,返回一个展开矩阵在该位置的元素(0表示对角线以下,值表示对角线以上)。我在考虑使用通常的矩阵乘法算法,每当需要访问元素时,它都会使用这个函数。我已经做了几个小时了,我想不出一种方法来将双矩阵索引(I,j)(I沿着行)转换为单数组索引,反之亦然(只是提醒一下,我正在使用一维数组来存储上三角矩阵)。如有任何帮助,我们将不胜感激!

// mat is an array containing the upper triangle data for a square matrix of size n
// returns element at (i,j), or 0 for the lower triangle
int getFromTriangle(const int* mat, int n, int i, int j)
{
  if (i > j) {
    return 0; // lower triangle
  } else {
    return mat[j + (i*n) - i*(i+1)/2];
  }
}

if子句负责处理下三角。else子句计算数组索引如下:

j + (i*n) - i*(i+1)/2

它只是正则矩形矩阵索引函数减去偏移量,该偏移量恰好是第i个三角数,因为在任何行i中,存储器都省略了triangle(i)元素。

您可以将算法划分为更小、易于理解的块。

// Get the array index given the rank, the row, and the column.
int getArrayIndex(int rank, int row, int col)
{
   return (row*rank + col - col*(col+1)/2);
}
// Get the term of a matrix, given the rank, the row, and the column.
int getMatrixTerm(int a[], int rank, int row, int col)
{
   if ( col < row )
   {
      return 0;
   }
   else
   {
      return a[getArrayIndex(rank, row, col)];
   }
}
// Get the term for a row and column resulting from mulitiplication.
int getMultipliedTerm(int a[], int b[], int rank, int row, int col)
{
   int term = 0;
   int k = 0;
   for ( ; k < rank; ++k )
   {
      term += getMatrixTerm(a, rank, row, k)*getMatrixTerm(b, rank, k, col);
   }
   return term;
}
// Set the term in c given the rank, the row, and the column.
void setMultipliedTerm(int a[], int b[], int c[], int rank, int row, int col)
{
   if ( j >= i )
   {
      c[getArrayIndex(rank, i, j)] = getMultipliedTerm(a, b, rank, i, j);
   }
}
// High level function to multiply two upper triangular matrices
// The lower part of the matrix is not stored at all.
void multiply(int a[], int b[], int c[], int rank)
{
   int i = 0;
   int j = 0;
   for ( i = 0; i < rank; ++i )
   {
      for ( j = 0; j < rank; ++j )
      {
         setMultipliedTerm(a, b, c, rank, i, j);
      }
   }
}

if p=&则a[i][j]与c++中的*(p+i*row_size+j)相同。其中p是指向与矩阵元素相同类型的数据的指针。我希望这是你想要的,而且你知道指针。一切都好。