-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtriangular_matrix.metta
More file actions
68 lines (62 loc) · 2.29 KB
/
triangular_matrix.metta
File metadata and controls
68 lines (62 loc) · 2.29 KB
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
;;; Replaces zeros in a row vector upto a given index from the left.
;;; Parameters: $n - an index upto which zeros are replaced
;;; $row - the row vector to process
;;; E.g, (replace_zeros_left 2 (1 2 3 4)) returns (0 0 3 4)
(= (replace_zeros_left $n $row)(
if (== $n 0) $row
( let $t (replace_zeros_left (- $n 1) (cdr-atom $row))
(cons-atom 0 $t)
)
))
;;; Replaces zeros in a row vector starting from a given index.
;;; Parameters: $n - the last number of elements to replace
;;; $row - the row vector to process
;;; E.g, (replace_zeros_right 2 (1 2 3 4)) returns (1 2 0 0)
(= (replace_zeros_right $n $row)(
if (== $row ()) () (
let* (
(($h $t)(decons-atom $row))
($replaced ( if (> (size-atom $row) $n) $h 0))
($rest (replace_zeros_right $n $t))
) (cons-atom $replaced $rest)
)
))
;;;; Generates an upper triangular matrix from a given matrix.
;;; Parameters: $matrix - the matrix to process
;;; Returns: An upper triangular matrix with zeros replaced in the appropriate positions.
(= (to_upr_matrix $matrix)(collapse (_to_upr_matrix $matrix)))
(= (_to_upr_matrix $matrix)(_to_upr_matrix $matrix 0))
(= (_to_upr_matrix $matrix $index)(
if (== $index (size-atom $matrix))
(empty)
(_to_upr_matrix $matrix (+ $index 1))
))
(= (_to_upr_matrix $matrix $index)(
replace_zeros_left $index (index-atom $matrix $index)
))
;;;; Generates a lower triangular matrix from a given matrix.
;;;; Parameters: $matrix - the matrix to process
;;;; Returns: A lower triangular matrix with zeros replaced in the appropriate positions.
(= (to_lwr_matrix $matrix)(collapse (_to_lwr_matrix $matrix)))
(= (_to_lwr_matrix $matrix)(_to_lwr_matrix $matrix 0))
(= (_to_lwr_matrix $matrix $index)(
if (== $index (size-atom $matrix))
(empty)
(_to_lwr_matrix $matrix (+ $index 1))
))
(= (_to_lwr_matrix $matrix $index)(
replace_zeros_right (- (- (size-atom $matrix) $index) 1) (index-atom $matrix $index)
))
;;; Example usage of the to_upr_matrix function
!(to_upr_matrix (
(1 2 3 4)
(4 5 6 7)
(7 8 9 2)
(4 8 2 9)
)) ; ((1 2 3 4) (0 5 6 7) (0 0 9 2) (0 0 0 9))
!(to_lwr_matrix (
(1 2 3 4)
(4 5 6 7)
(7 8 9 2)
(4 8 2 9)
)) ; ((1 0 0 0) (4 5 0 0) (7 8 9 0) (4 8 2 9))