summaryrefslogtreecommitdiff
path: root/LA/Lib/Matrix.swift
blob: 8b3f538a76e576d27de765dfaa66d13fe8f97b1d (plain) (blame)
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
63
64
65
66
67
68
69
70
71
72
73
//
//  Matrix.swift
//  PrySDR
//
//  Created by Jacky Jack on 20/10/2024.
//

enum MatrixOperationError:Error {
    case columnValue
    case rowValue
}

/// Matrix Data Type
class Matrix {
    /// matrix row number
    let rows: Int
    /// matrix column number
    let columns: Int
    /// array where matrix is stored
    var data: [Float]
    
    /// Create NxM matrix
    /// - Parameters:
    ///   - rows: number of rows in matrix
    ///   - columns: number of columns in matrix
    ///   - val: default value of matrix elements
    init(rows: Int, columns: Int, val: Float) throws {
        if (rows < 1) {
            throw MatrixOperationError.columnValue
        }
        if (columns < 1) {
            throw MatrixOperationError.rowValue
        }
        self.rows = rows
        self.columns = columns
        self.data = Array(repeating: 0.0, count: rows*columns)
        //print(self.data)
    }
    
    /// Set elements to value
    /// - Parameters:
    ///   - val: value to set
    func set(_ val: Float) {
        for idx in 0..<self.data.count {
            self.data[idx] = val
        }
    }
    /// Set all elements to 0
    func zero() {
        self.set(0.0)
    }
    
    /// Set all elements to 1
    func one() {
        self.set(1.0)
    }
}

/// Return 0 matrix
/// - Parameters:
///   - rows: number of rows in matrix
///   - columns: number of columns in matrix
func zero(_ rows: Int, _ columns: Int) -> Matrix {
    return try! Matrix.init(rows: rows, columns: columns, val: 0.0)
}

/// Return identity matrix
/// - Parameters:
///   - rows: number of rows in matrix
///   - columns: number of columns in matrix
func one(_ rows: Int, _ columns: Int) -> Matrix {
    return try! Matrix.init(rows: rows, columns: columns, val: 1.0)
}