繁体   English   中英

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

[英]error in c++ matrix*vector multiplication

我需要一个将矩阵和向量相乘的 function (Matrix*vector)

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

如果 function 返回一个 boolean 值,例如指示 function 执行是否成功,那就更好了

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而不是手动编写的循环。

暂无
暂无

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

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