我需要一个将矩阵和 vector 相乘的函数(矩阵* vector )
它接受一个矩阵 A 和一个 vector B,用 int 描述维度。不知怎的,它运行不正确。有什么帮助吗??
void Multiply(double *res, double **A, double *B, int ARows, int ACols, int BRows)
{
if (ACols !=BRows)
{
return;
}
for (int i = 0; i < ACols; i++)
{
res[i] = 0;
for (int j = 0; j < BRows; j++)
{
res[i] += A[i][j]*B[j];
}
}
}
最佳答案
看来你的意思是
for (int i = 0; i < ARows; i++)
{
res[i] = 0;
for (int j = 0; j < ACols; j++)
{
res[i] += A[i][j]*B[j];
}
}
如果函数返回一个 bool 值来表示函数执行是否成功,那就更好了
bool Multiply(double *res, double **A, double *B, int ARows, int ACols, int BRows)
{
bool success = ACols == BRows;
if ( success )
{
for (int i = 0; i < ARows; i++)
{
res[i] = 0;
for (int j = 0; j < ACols; j++)
{
res[i] += A[i][j]*B[j];
}
}
}
return success;
}
您可以使用标准算法 std::inner_product
而不是手动编写的循环。在 header <numeric>
中声明.
关于c++ - C++矩阵* vector 乘法中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67971662/