C ++矩阵*向量乘法中的错误

error in c++ matrix*vector multiplication

我需要一个矩阵和向量相乘的函数(矩阵*向量)

它接受一个矩阵 A 和一个向量 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];
    }
}

如果函数returns一个表示函数执行是否成功的布尔值就更好了,例如

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;
} 

您可以使用在 header <numeric>.

中声明的标准算法 std::inner_product 而不是手动编写的循环