Skip to content

Instantly share code, notes, and snippets.

@Swarchal
Created June 22, 2016 09:42
Show Gist options
  • Save Swarchal/8fb0726685f3e327d1edbe75e4fd814d to your computer and use it in GitHub Desktop.
Save Swarchal/8fb0726685f3e327d1edbe75e4fd814d to your computer and use it in GitHub Desktop.
#include <Rcpp.h>
using namespace Rcpp;
// cosine distance between two vectors
double cosv(NumericVector a, NumericVector b)
{
double theta;
theta = sum(a * b) / sqrt(sum(pow(a, 2)) * sum(pow(b, 2)));
return theta;
}
// initialise an Rcpp matrix
NumericMatrix M(int row, int col)
{
NumericMatrix mat(row, col);
return mat;
}
// fill matrix with values calculated from cosine similarities
// [[Rcpp::export]]
NumericMatrix cosv_matrix(int nrow, int ncol, NumericVector a, NumericVector b)
{
// create matrix to store values
NumericMatrix M(nrow, ncol);
for (int i = 0; i < nrow; i++)
{
for (int j = 0; j < ncol; j++)
{
M[i, j] = cosv(a, b); // need to get the vectors from the dataframe
// ideally without writing a separate loop
}
}
return M;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment