STL Inner Product

Dirk Eddelbuettel — Dec 27, 2012 | source

The STL contains a large number of useful functions and algorithm. One useful function is inner_product which can be used to compute the sum oof the elements of two vectors.

#include <Rcpp.h>
#include <numeric>

// [[Rcpp::export]]
double innerProduct(const std::vector<double>& x, 
                    const std::vector<double>& y) {
    double val = std::inner_product(x.begin(), x.end(), y.begin(), 0);
    return val;
}
x <- c(1,2,3)
y <- c(4,5,6)
cbind(x,y)
     x y
[1,] 1 4
[2,] 2 5
[3,] 3 6
innerProduct(x, y)
[1] 32
sum(x*y)  # check from R
[1] 32
innerProduct(x, x)
[1] 14
sum(x^2)
[1] 14

tags: stl 

Related Articles