乘法矩阵(c++)的算法有问题
Trouble with algorithm for multiplying matrix (c++)
嗨,我正在帮我的一个朋友写一个程序,可以在不扩展矩阵的情况下将两个上三角矩阵相乘。当我说不展开矩阵时,我的意思是不用零填充上三角矩阵的下部(目标是节省空间)。我正在从一个文件中读取矩阵,该文件只包含矩阵的上三角值,省略了下部分。
我试图完成的是编写一个函数,在给定一个数组和一对索引的情况下,返回一个展开矩阵在该位置的元素(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是指向与矩阵元素相同类型的数据的指针。我希望这是你想要的,而且你知道指针。一切都好。
相关文章:
- 我似乎对if/else的基本语句有问题:/
- 到连接组件算法的问题(递归)
- 我在范围内未声明的错误类有问题
- 这种用于查找连续子数组中最大和的递归算法有什么优势吗?
- 我的C++语言蛮力算法有问题
- 我关于函数"Assert"的C++代码有问题
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- C++类中的友元函数有问题?
- 我对数组即 0x6dfe78 有问题
- 我对 std::unique(算法)C++有问题
- 这种快速排序算法有什么问题?
- 我的记忆动态规划算法有什么问题?
- 这种递归算法有什么问题?
- 拉盖尔插值算法,我的实现有问题
- Gale Shapley算法的实现有问题
- C++中的合并函数算法有问题
- 我的算法有什么问题?
- 乘法矩阵(c++)的算法有问题
- 我的dijkstras算法有什么问题?
- 我的交集检查算法有什么问题