14-linear-algebra/02-matrix-operations.protos

Repository
guillermomolina/protos
Commit
379c6fa63685c39a5954cfbd577bfda3b4df8e75
Tree
8cd4f4afe29ae4c3866381f38c1858108e9799f6
Blob
19dca9c325009c875941679086441c126de92ab5
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

// A Matrix takes its dimensions first, then exactly rows * columns values in
// row-major order. Elements are read with at(row, column); there is no
// m[row, column] form.

LA: import("std:math/linear_algebra")
Vector: LA.Vector
Matrix: LA.Matrix

// Rows: [1, 2, 3] and [4, 5, 6].
m: Matrix(2, 3, 1, 2, 3, 4, 5, 6)
print(m.rows())
print(m.columns())
print(m.at(1, 0))

// matvec: each result element is one row times the Vector.
image: m.matvec(Vector(1, 0, 1))     // 1 + 3, 4 + 6
print(image[1])

// matmul: a 2 × 3 times a 3 × 2 Matrix is 2 × 2.
n: Matrix(3, 2, 7, 8, 9, 10, 11, 12)
product: m.matmul(n)                 // rows [58, 64] and [139, 154]

// Multiplying by a unit Vector selects one column: column 0, then column 1.
first: product.matvec(Vector(1, 0))
second: product.matvec(Vector(0, 1))
print(first[0])
print(second[1])

// transpose answers a new 3 × 2 Matrix; m itself is unchanged.
t: m.transpose()

// Contextual for sends ordinary each, visiting a shallow snapshot in order.
visitedTotal: 0
traversed: for(n in m) {
    visitedTotal = visitedTotal + n
}
print(visitedTotal)

verified: (traversed === m) && (visitedTotal == 21) &&
    (m.rows() == 2) && (m.columns() == 3) &&
    (image.size() == 2) && (image[0] == 4) && (image[1] == 10) &&
    (product.rows() == 2) && (product.columns() == 2) &&
    (first[0] == 58) && (second[0] == 64) &&
    (first[1] == 139) && (second[1] == 154) &&
    (t.rows() == 3) && (t.columns() == 2) && (t.at(2, 1) == 6)
// A wrong result must fail the program, not print false.
if(!verified) {
    Error().signal()
}
print(verified)