简体   繁体   English

如何在 c++ 中的矩阵和向量之间进行点积

[英]How can I do a dot product between a matrix and a vector in c++

There are a function called inner_product , but I failed miserably in use that.有一个名为inner_product的 function ,但我在使用它时失败了。 I'll need to use this function several times for different matrices and vectors.对于不同的矩阵和向量,我需要多次使用这个 function。 Bellow my current code:咆哮我当前的代码:

std::vector<vector<int>> matrix_a = {{0, 0},
                                     {0, 1},
                                     {1, 0},
                                     {1, 1}};
std::vector<float> vector_b = {0.5, 0.8};

dot_produt(matrix_a, vettor_b);
float dot_produt(vector<vector<int>> e, vector<float> p){
    return std::inner_product(std::begin(e), std::end(e), std::begin(p), 0.0);
}

The process is like:过程是这样的:

(0.5 * 0) + (0.8 * 0) + (0.5 * 0) + (0.8 * 1)... ...

Expected output:预期 output:

2.6

Error:错误:

no match for 'operator*' (operand types are 'std::vector<int>' and 'float')
__init = __init + (*__first1 * *__first2);

You are trying to use pointers to begin and end of a vector of vectors, inner_product requires pointers to beginning and end of a vector.您正在尝试使用指针来开始和结束向量向量, inner_product需要指向向量开始和结束的指针。

Also, vectors have their own iterators, you can use them instead of std::begin and std::end .此外,向量有自己的迭代器,您可以使用它们来代替std::beginstd::end

Live demo现场演示

#include <iostream>
#include <numeric>
#include <vector>

//passing vectors by reference avoids unnecessary copies
double dot_produt(const std::vector<std::vector<int>> &e, const std::vector<float> &p)
{
    double result = 0;
    for (auto& v : e) //range based loop
        result += std::inner_product(v.begin(), v.end(), p.begin(), 0.0);
    return result;
}

int main()
{
    std::vector<std::vector<int>> matrix_a = {{0, 0},
                                              {0, 1},
                                              {1, 0},
                                              {1, 1}};
    std::vector<float> vector_b = {0.5, 0.8};

    std::cout << dot_produt(matrix_a, vector_b); //test print
}

Output: Output:

2.6

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

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