mirror of
https://github.com/ml-explore/mlx.git
synced 2025-12-16 01:49:05 +08:00
Add matrix inversion primitive (#822)
This commit is contained in:
@@ -238,4 +238,27 @@ std::vector<array> svd(const array& a, StreamOrDevice s /* = {} */) {
|
||||
{a});
|
||||
}
|
||||
|
||||
array inv(const array& a, StreamOrDevice s /* = {} */) {
|
||||
if (a.dtype() != float32) {
|
||||
std::ostringstream msg;
|
||||
msg << "[linalg::inv] Arrays must type float32. Received array "
|
||||
<< "with type " << a.dtype() << ".";
|
||||
throw std::invalid_argument(msg.str());
|
||||
}
|
||||
if (a.ndim() < 2) {
|
||||
std::ostringstream msg;
|
||||
msg << "[linalg::inv] Arrays must have >= 2 dimensions. Received array "
|
||||
"with "
|
||||
<< a.ndim() << " dimensions.";
|
||||
throw std::invalid_argument(msg.str());
|
||||
}
|
||||
if (a.shape(-1) != a.shape(-2)) {
|
||||
throw std::invalid_argument(
|
||||
"[linalg::inv] Inverses are only defined for square matrices.");
|
||||
}
|
||||
|
||||
return array(
|
||||
a.shape(), a.dtype(), std::make_unique<Inverse>(to_stream(s)), {a});
|
||||
}
|
||||
|
||||
} // namespace mlx::core::linalg
|
||||
|
||||
Reference in New Issue
Block a user