# distance method

num distance(
1. Vector other, {
2. DistanceType distance = DistanceType.frobenius,
})

Sets all elements of this vector to `value`.

Example:

``````var v = Vector.fromList([1, 2, 3]);
v.setAll(0);
print(v);
``````

Output:

``````[0, 0, 0]
``````

Returns the Euclidean distance between this vector and `other`.

The distance is given by the formula `sqrt(sum((this[i] - other[i])^2))` for all i.

Throws an `ArgumentError` if the vectors have different lengths.

Example:

``````var v1 = Vector.fromList([1, 2, 3]);
var v2 = Vector.fromList([4, 5, 6]);
print(v1.distance(v2));
``````

Output:

``````5.196152422706632
``````

## Implementation

``````// void setAll(num value) {
//   for (var i = 0; i < length; i++) {
//     this[i] = value;
//   }
// }

/// Returns the Euclidean distance between this vector and [other].
///
/// The distance is given by the formula `sqrt(sum((this[i] - other[i])^2))` for all i.
///
/// Throws an `ArgumentError` if the vectors have different lengths.
///
/// Example:
/// ```dart
/// var v1 = Vector.fromList([1, 2, 3]);
/// var v2 = Vector.fromList([4, 5, 6]);
/// print(v1.distance(v2));
/// ```
///
/// Output:
/// ```
/// 5.196152422706632
/// ```
num distance(Vector other, {DistanceType distance = DistanceType.frobenius}) {
if (length != other.length) {
throw ArgumentError(
"Vectors must have the same length for distance calculation.");
}

double sumSquare = 0;
double sumAbs = 0;
num maxAbs = 0;
double dotProduct = 0;
double sumSquare1 = 0;
double sumSquare2 = 0;
int hammingDistance = 0;

for (int i = 0; i < _data.length; i++) {
final diff = _data[i] - other[i];
final absDiff = diff.abs();

sumSquare += diff * diff;
sumAbs += absDiff;
maxAbs = math.max(maxAbs, absDiff);
dotProduct += _data[i] * other[i];
sumSquare1 += _data[i] * _data[i];
sumSquare2 += other[i] * other[i];
hammingDistance += _data[i] != other[i] ? 1 : 0;
}

switch (distance) {
case DistanceType.frobenius:
return math.sqrt(sumSquare);
case DistanceType.manhattan:
return sumAbs;
case DistanceType.chebyshev:
return maxAbs;
case DistanceType.mahalanobis:
// We need a covariance matrix and its inverse to compute Mahalanobis distance
return double.nan; // placeholder value indicating unimplemented
case DistanceType.cosine:
final magnitude1 = math.sqrt(sumSquare1);
final magnitude2 = math.sqrt(sumSquare2);
return 1 - (dotProduct / (magnitude1 * magnitude2));
case DistanceType.hamming:
return hammingDistance;
case DistanceType.spectral:
// For vectors, we consider spectral norm as its magnitude
//return math.sqrt(sumSquare);
case DistanceType.trace:
// For vectors, we consider trace norm as the sum of its elements
//return sumAbs;
default:
throw Exception('Invalid distance type');
}
}``````