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()use std::ops::{Index, IndexMut};
 
let m = matrix_from_vec(vec!(
fn main() {
2, -1, 5, 1,
let m = 3, 2, 2, -6,matrix(
1, 3, 3, -1,vec![
2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3.,
)],
4);,
);
let mm = m.solve(&vec!([-3., -32., -47., 49).]);
println!("{:?}", mm);
}
Line 1,736 ⟶ 1,737:
#[derive(Clone)]
struct Matrix {
elts : Vec<Vec<i64>f64>,
dim: usize,
}
 
impl Matrix {
// Compute determinant with theusing cofactor method
// 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.elts[0][0] as f64,
2 => (self.elts[0][0] * self.elts[1][1] - self.elts[0][1] * self.elts[1][0]) as f64,
d => {
let mut acc = 0.;
let mut coeffsignature = 1.;
for k in 0..d {
acc += coeffsignature * self.elts[0][k] as f64 * self.comatrix(0, k).det();
coeffsignature *= -1.
}
acc
Line 1,762 ⟶ 1,763:
 
// Solve linear systems using Cramer's method
fn solve(&self, target : &Vec<i64f64>) -> Vec<f64> {
let mut solution : Vec<f64> = vec!([0.; self.dim)];
let denominator = self.det();
for j in 0..self.dim {
let mut mm = self.clone();
for i in 0..self.dim { mm.elts[i][j] = target[i] }
mm[i][j] = target[i]
}
solution[j] = mm.det() / denominator
}
Line 1,773 ⟶ 1,776:
}
 
// Compute athe cofactor matrix for determinant computationcomputations
fn comatrix(&self, k : usize, l : usize) -> Matrix {
let mut v : Vec<i64f64> = vec!()[];
for i in 0..self.dim {
for j in 0..self.dim {
if i != k && j != l { v.push(self.elts[i][j]) }
v.push(self[i][j])
2, -1, 5, 1, }
}
}
matrix_from_vecmatrix(v, self.dim - 1)
}
}
 
fn matrix(elts: Vec<f64>, dim: usize) -> Matrix {
assert_eq!(elts.len(), dim * dim);
Matrix { elts, dim }
}
 
fnimpl matrix_from_vec(v : VecIndex<i64usize>, dim : usize) ->for Matrix {
assert_eq!(v.len(),type dimOutput *= dim)[f64];
 
let mut elts = vec!(vec!(0; dim); dim);
forfn index(&self, i: usize) in-> 0..dim&Self::Output {
forlet jm in= 0.self.dim {;
&self.elts[i][j]m =* v[i..m * dim(i + j1)]
}
}
 
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>