Anonymous user
Cramer's rule: Difference between revisions
→{{header|Rust}}: Implement access by index to matrices and cleaning the code
(Add Rust version) |
(→{{header|Rust}}: Implement access by index to matrices and cleaning the code) |
||
Line 1,722:
=={{header|Rust}}==
<lang Rust>
fn main() {
2, -1, 5, 1,▼
let m =
2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3.,
);
let mm = m.solve(&vec!
println!("{:?}", mm);
}
Line 1,736 ⟶ 1,737:
#[derive(Clone)]
struct Matrix {
elts
dim: usize,
}
impl Matrix {
// Compute determinant
// Using Gaussian elimination would have been more efficient, but it also solves the linear
// system, so…
Line 1,747 ⟶ 1,748:
match self.dim {
0 => 0.,
1 => self
2 =>
d => {
let mut acc = 0.;
let mut
for k in 0..d {
acc +=
}
acc
Line 1,762 ⟶ 1,763:
// Solve linear systems using Cramer's method
fn solve(&self, target
let mut solution
let denominator = self.det();
for j in 0..self.dim {
let mut mm = self.clone();
for i in 0..self.dim {
mm[i][j] = target[i]
}
solution[j] = mm.det() / denominator
}
Line 1,773 ⟶ 1,776:
}
// Compute
fn comatrix(&self, k
let mut v
for i in 0..self.dim {
for j in 0..self.dim {
if i != k && j != l {
v.push(self[i][j])
}
}
}
}
fn matrix(elts: Vec<f64>, dim: usize) -> Matrix {
assert_eq!(elts.len(), dim * dim);
Matrix { elts, dim }▼
}
}
impl IndexMut<usize> for Matrix {
fn index_mut(&mut self, i: usize) -> &mut Self::Output {
let m = self.dim;
&mut self.elts[m * i..m * (i + 1)]
}
▲ Matrix { elts, dim }
}</lang>
|