1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use crate::{matrix::Matrix, number::c64};
use lapack::dgesv;
use lapack::zgesv;
use std::mem::transmute;

impl Matrix {
    /// # Inverse
    /// for square matrix
    pub fn geinv(self) -> Result<Matrix, String> {
        let mut slf = self;
        let mut ipiv = vec![0; slf.rows];
        let mut solution_matrix = Matrix::identity(slf.rows);
        let mut info = 0;

        unsafe {
            dgesv(
                slf.rows as i32,
                slf.rows as i32,
                &mut slf.elements,
                slf.rows as i32,
                &mut ipiv,
                &mut solution_matrix.elements,
                slf.rows as i32,
                &mut info,
            );
        }

        match info {
            0 => Ok(solution_matrix),
            i => Err(i.to_string()),
        }
    }
}

impl Matrix<c64> {
    /// # Inverse
    /// for square matrix
    pub fn geinv(self) -> Result<Matrix<c64>, String> {
        let mut slf = self;
        let mut ipiv = vec![0; slf.rows];
        let mut solution_matrix = Matrix::<c64>::identity(slf.rows);
        let mut info = 0;

        unsafe {
            zgesv(
                slf.rows as i32,
                slf.rows as i32,
                transmute::<&mut [c64], &mut [blas::c64]>(&mut slf.elements),
                slf.rows as i32,
                &mut ipiv,
                transmute::<&mut [c64], &mut [blas::c64]>(&mut solution_matrix.elements),
                slf.rows as i32,
                &mut info,
            );
        }

        match info {
            0 => Ok(solution_matrix),
            i => Err(i.to_string()),
        }
    }
}