distance method
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
/// ```
Complex distance(Vector other,
{DistanceType distance = DistanceType.frobenius}) {
if (length != other.length) {
throw ArgumentError(
"Vectors must have the same length for distance calculation.");
}
Complex sumSquare = Complex.zero();
Complex sumAbs = Complex.zero();
Complex maxAbs = Complex.zero();
Complex dotProduct = Complex.zero();
Complex sumSquare1 = Complex.zero();
Complex sumSquare2 = Complex.zero();
Complex hammingDistance = Complex.zero();
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] ? Complex.one() : Complex.zero();
}
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 Complex.nan(); // placeholder value indicating unimplemented
case DistanceType.cosine:
final magnitude1 = math.sqrt(sumSquare1);
final magnitude2 = math.sqrt(sumSquare2);
return Complex.one() - (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');
}
}