Skip to content
Snippets Groups Projects
Unverified Commit 384d9559 authored by STEVAN Antoine's avatar STEVAN Antoine :crab:
Browse files

ask ChatGPT for the correct rank algorithm

the prompt was
> how to compute the rank of a matrix in Rust? below is the structure of a matrix
>
> ```
> pub struct Matrix<T: Field> {
>     pub elements: Vec<T>,
>     pub height: usize,
>     pub width: usize,
> }
> ```
parent e27561bb
No related branches found
No related tags found
No related merge requests found
......@@ -165,34 +165,49 @@ impl<T: Field> Matrix<T> {
}
pub fn rank(&self) -> usize {
let mut matrix = self.clone();
let mut mat = self.elements.clone();
let mut rank = 0;
let mut i = 0;
for i in 0..matrix.height.min(matrix.width) {
let pivot = matrix.get(i, i);
if pivot.is_zero() {
continue;
for j in 0..self.width {
let mut found = false;
for k in i..self.height {
if mat[k * self.width + j] != T::zero() {
// Swap the rows to move the non-zero element to the diagonal
mat.swap(
i * self.width..(i + 1) * self.width,
k * self.width..(k + 1) * self.width,
);
found = true;
break;
}
}
matrix.divide_row_by(i, pivot);
if found {
for k in (i + 1)..self.height {
let ratio = mat[k * self.width + j] / mat[i * self.width + j];
for l in j..self.width {
mat[k * self.width + l] -= ratio * mat[i * self.width + l];
}
}
i += 1;
}
}
for k in 0..matrix.height {
if k != i {
let factor = matrix.get(k, i);
matrix.multiply_row_by_and_add_to_row(i, -factor, k);
for i in 0..self.height {
let mut all_zeros = true;
for j in 0..self.width {
if mat[i * self.width + j] != T::zero() {
all_zeros = false;
break;
}
}
if !all_zeros {
rank += 1;
}
}
matrix.height
- (0..matrix.height)
.map(|i| {
let row =
matrix.elements[(i * matrix.width)..((i + 1) * matrix.width)].to_vec();
row.iter().all(|&x| x.is_zero())
})
.filter(|&r| r)
.collect::<Vec<_>>()
.len()
rank
}
pub(super) fn mul(&self, rhs: &Self) -> Result<Self, KomodoError> {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment