Sunday, January 26, 2014

Vector distance and norm in la4j

The la4j API allows you to calculate the vector norm easily with appropriate vector accumulator. There are three norm accumulators available: Euclidean, Manhattan and Infinity. So, you can use them as fold arguments in a way like this:
Vector a = new BasicVector(new double[]{ 1.0, 2.0, 3.0 });
doble norm0   = a.fold(Vectors.mkEuclideanNormAccumulator()); // Euclidean Norm
doble norm1   = a.fold(Vectors.mkManhattanNormAccumulator()); // Manhattan Norm
doble normMax = a.fold(Vectors.mkInfinityNormAccumulator());  // Infinity Norm
When norm is available, the distance between two vectors can be calculated as:
Vector a = new BasicVector(new double[]{ 1.0, 2.0, 3.0 });
Vector b = new BasicVector(new double[]{ 4.0, 5.0, 6.0 });
// the distance between vectors 'a' and 'b' in terms of Manhattan space
double distance = a.subtract(b).fold(Vectors.mkManhattanNormAccumulator());
You also can use norm in order to normalize the vector's components:
Vector a = new BasicVector(new double[]{ 1.0, 2.0, 3.0 });
double norm = a.fold(Vectors.mkEuclideanNormAccumulator());
// normalize 'b' in terms of Eucludean space
Vector b = a.divide(norm);

No comments:

Post a Comment