Added `var shape: Shape` to `Matrix<Scalar>` (with possible values `.tall`, `.wide`, `.square`)

This commit is contained in:
Vincent Esche 2019-10-16 14:04:15 +02:00
parent bbbfbd722e
commit 2f35e09724
2 changed files with 55 additions and 2 deletions

View File

@ -26,13 +26,28 @@ public enum MatrixAxies {
}
public struct Matrix<Scalar> where Scalar: FloatingPoint, Scalar: ExpressibleByFloatLiteral {
public enum Shape: Equatable {
// `self.rows < self.columns` (aka. `m < n`)
case wide
/// `self.rows > self.columns` (aka. `m > n`)
case tall
// `self.rows == self.columns` (aka. `m == n`)
case square
}
public let rows: Int
public let columns: Int
var grid: [Scalar]
public var isSquare: Bool {
return self.rows == self.columns
public var shape: Shape {
if self.rows > self.columns {
return .tall
} else if self.rows < self.columns {
return .wide
} else {
return .square
}
}
// MARK: - Initialization

View File

@ -225,6 +225,44 @@ class MatrixTests: XCTestCase {
XCTAssertEqual(actual_3x3, expected_3x3)
}
// MARK: - Shape
func test_shape_tall() {
typealias Scalar = Double
let matrix: Matrix<Scalar> = [
[1, 2],
[3, 4],
[5, 6],
[7, 8],
]
XCTAssertEqual(matrix.shape, .tall)
}
func test_shape_wide() {
typealias Scalar = Double
let matrix: Matrix<Scalar> = [
[1, 2, 3, 4],
[5, 6, 7, 8],
]
XCTAssertEqual(matrix.shape, .wide)
}
func test_shape_square() {
typealias Scalar = Double
let matrix: Matrix<Scalar> = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
XCTAssertEqual(matrix.shape, .square)
}
// MARK: - Subscript
func test_subscript_row_get() {