1

I try to create a similarity matrix with eigen library on a dataset. I just read the csv file into eigen matrix but know as a matlab customer I am looking for something like bsxfun or something to define the distances between instances by Euclidean distance calculation.How can I get away with a solution or what sources, functions might help me ?

Amro
  • 123,847
  • 25
  • 243
  • 454
erogol
  • 13,156
  • 33
  • 101
  • 155
  • I'm pretty sure that `Eigen` library is capable to calculate Euclidean distance between matrices. – fpe Aug 22 '13 at 21:54

1 Answers1

3

Assuming your samples are stored row-wise in a matrix D, then you can do:

VectorXd N = D.rowwise().squaredNorm();
MatrixXd S = N.replicate(1,n) + N.transpose().replicate(n,1);
S.noalias() -= 2. * D * D.transpose();
S = S.array().sqrt();

This exploits the fact that |x-y|²=x²+y²-2x'y. The noalias() statement is just an optimization to Eigen there is no risk of aliasing in this product, thus no temporary is needed. The .array() statement switches to the array world where all functions are applied coefficient-wise.

ggael
  • 28,425
  • 2
  • 65
  • 71
  • +1 here is a similar MATLAB code: http://stackoverflow.com/a/4171845/97160 (although that worked on the columns of the matrix, rather than on the rows) – Amro Aug 23 '13 at 01:24
  • Only the core module is needed: `#include ` – ggael Aug 23 '13 at 09:27
  • Also for being generic solution I need to get the n = N.size(). Simple N.size() works, right ? – erogol Aug 23 '13 at 09:29