【问题标题】:error in c++ matrix*vector multiplicationC++矩阵*向量乘法中的错误
【发布时间】:2021-08-30 10:38:04
【问题描述】:

我需要一个将矩阵和向量相乘的函数 (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];
        }
    }
}

【问题讨论】:

  • 不应该在某处使用ARows吗?
  • 首先应该是 Arows,而不是 Acols。注意res的行数和A一样,分配正确了吗?
  • 也许std::valarray 可以提供帮助。

标签: c++ loops for-loop nested-loops function-definition


【解决方案1】:

看来你的意思

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

您可以使用在标头&lt;numeric&gt; 中声明的标准算法std::inner_product,而不是手动编写的循环。

【讨论】:

  • 又名res[i] = std::inner_product(A[i], A[i] + ACols, B, 0);
猜你喜欢
  • 1970-01-01
  • 2020-03-16
  • 2012-11-24
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多