-
Notifications
You must be signed in to change notification settings - Fork 86
/
Matrix.swift
executable file
·1384 lines (1211 loc) · 37.1 KB
/
Matrix.swift
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Matrix.swift
//
// Copyright (c) 2016 Matthijs Hollemans
// Copyright (c) 2014-2015 Mattt Thompson (http://mattt.me)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Accelerate
public struct Matrix {
public let rows: Int
public let columns: Int
var grid: [Double]
}
// MARK: - Creating matrices
extension Matrix {
public init(rows: Int, columns: Int, repeatedValue: Double) {
self.rows = rows
self.columns = columns
self.grid = .init(repeating: repeatedValue, count: rows * columns)
}
public init(size: (Int, Int), repeatedValue: Double) {
self.init(rows: size.0, columns: size.1, repeatedValue: repeatedValue)
}
/* Creates a matrix from an array: [[a, b], [c, d], [e, f]]. */
public init(_ data: [[Double]]) {
self.init(data, range: 0..<data[0].count)
}
/* Extracts one or more columns into a new matrix. */
public init(_ data: [[Double]], range: CountableRange<Int>) {
let m = data.count
let n = range.upperBound - range.lowerBound
self.init(rows: m, columns: n, repeatedValue: 0)
/*
for (i, row) in data.enumerate() {
for j in range {
self[i, j - range.startIndex] = row[j]
}
}
*/
for (i, row) in data.enumerated() {
row.withUnsafeBufferPointer { src in
grid.withUnsafeMutableBufferPointer{ gridPtr in
cblas_dcopy(Int32(n), src.baseAddress! + range.lowerBound, 1, gridPtr.baseAddress! + i*columns, 1)
}
}
}
}
public init(_ data: [[Double]], range: CountableClosedRange<Int>) {
self.init(data, range: CountableRange(range))
}
/* Creates a matrix from a row vector or column vector. */
public init(_ contents: [Double], isColumnVector: Bool = false) {
if isColumnVector {
self.rows = contents.count
self.columns = 1
} else {
self.rows = 1
self.columns = contents.count
}
self.grid = contents
}
/* Creates a matrix containing the numbers in the specified range. */
public init(_ range: CountableRange<Int>, isColumnVector: Bool = false) {
if isColumnVector {
self.init(rows: 1, columns: range.upperBound - range.lowerBound, repeatedValue: 0)
for c in range {
self[0, c - range.lowerBound] = Double(c)
}
} else {
self.init(rows: range.upperBound - range.lowerBound, columns: 1, repeatedValue: 0)
for r in range {
self[r - range.lowerBound, 0] = Double(r)
}
}
}
public init(_ range: CountableClosedRange<Int>, isColumnVector: Bool = false) {
self.init(CountableRange(range), isColumnVector: isColumnVector)
}
}
extension Matrix {
/* Creates a matrix where each element is 0. */
public static func zeros(rows: Int, columns: Int) -> Matrix {
return Matrix(rows: rows, columns: columns, repeatedValue: 0)
}
public static func zeros(size: (Int, Int)) -> Matrix {
return Matrix(size: size, repeatedValue: 0)
}
/* Creates a matrix where each element is 1. */
public static func ones(rows: Int, columns: Int) -> Matrix {
return Matrix(rows: rows, columns: columns, repeatedValue: 1)
}
public static func ones(size: (Int, Int)) -> Matrix {
return Matrix(size: size, repeatedValue: 1)
}
/* Creates a (square) identity matrix. */
public static func identity(size: Int) -> Matrix {
var m = zeros(rows: size, columns: size)
for i in 0..<size { m[i, i] = 1 }
return m
}
/* Creates a matrix of random values between 0.0 and 1.0 (inclusive). */
public static func random(rows: Int, columns: Int) -> Matrix {
var m = zeros(rows: rows, columns: columns)
for r in 0..<rows {
for c in 0..<columns {
m[r, c] = Double(arc4random()) / 0xffffffff
}
}
return m
}
}
extension Matrix: ExpressibleByArrayLiteral {
/* Array literals are interpreted as row vectors. */
public init(arrayLiteral: Double...) {
self.rows = 1
self.columns = arrayLiteral.count
self.grid = arrayLiteral
}
}
extension Matrix {
/* Duplicates a row vector across "d" rows. */
public func tile(_ d: Int) -> Matrix {
precondition(rows == 1)
var m = Matrix.zeros(rows: d, columns: columns)
/*
for r in 0..<d {
for c in 0..<columns {
m[r, c] = self[0, c]
}
}
*/
grid.withUnsafeBufferPointer { src in
m.grid.withUnsafeMutableBufferPointer { dst in
for i in 0..<d {
// Alternatively, use memcpy instead of BLAS.
//memcpy(ptr, src.baseAddress, columns * MemoryLayout<Double>.stride)
cblas_dcopy(Int32(columns), src.baseAddress, 1, dst.baseAddress?.advanced(by: columns * i), 1)
}
}
}
return m
}
}
extension Matrix {
/* Copies the contents of an NSData object into the matrix. */
public init(rows: Int, columns: Int, data: NSData) {
precondition(data.length >= rows * columns * MemoryLayout<Double>.stride)
self.init(rows: rows, columns: columns, repeatedValue: 0)
grid.withUnsafeMutableBufferPointer { dst in
let src = UnsafePointer<Double>(OpaquePointer(data.bytes))
cblas_dcopy(Int32(rows * columns), src, 1, dst.baseAddress, 1)
}
}
/* Copies the contents of the matrix into an NSData object. */
public var data: NSData? {
if let data = NSMutableData(length: rows * columns * MemoryLayout<Double>.stride) {
grid.withUnsafeBufferPointer { src in
let dst = UnsafeMutablePointer<Double>(OpaquePointer(data.bytes))
cblas_dcopy(Int32(rows * columns), src.baseAddress, 1, dst, 1)
}
return data
} else {
return nil
}
}
}
// MARK: - Querying the matrix
extension Matrix {
public var size: (Int, Int) {
return (rows, columns)
}
/* Returns the total number of elements in the matrix. */
public var count: Int {
return rows * columns
}
/* Returns the largest dimension. */
public var length: Int {
return Swift.max(rows, columns)
}
public subscript(row: Int, column: Int) -> Double {
get { return grid[(row * columns) + column] }
set { grid[(row * columns) + column] = newValue }
}
/* Subscript for when the matrix is a row or column vector. */
public subscript(i: Int) -> Double {
get {
precondition(rows == 1 || columns == 1, "Not a row or column vector")
return grid[i]
}
set {
precondition(rows == 1 || columns == 1, "Not a row or column vector")
grid[i] = newValue
}
}
/* Get or set an entire row. */
public subscript(row r: Int) -> Matrix {
get {
var v = Matrix.zeros(rows: 1, columns: columns)
/*
for c in 0..<columns {
m[c] = self[r, c]
}
*/
grid.withUnsafeBufferPointer { src in
v.grid.withUnsafeMutableBufferPointer { dst in
cblas_dcopy(Int32(columns), src.baseAddress! + r*columns, 1, dst.baseAddress, 1)
}
}
return v
}
set(v) {
precondition(v.rows == 1 && v.columns == columns, "Not a compatible row vector")
/*
for c in 0..<columns {
self[r, c] = v[c]
}
*/
v.grid.withUnsafeBufferPointer { src in
grid.withUnsafeMutableBufferPointer{ gridPtr in
cblas_dcopy(Int32(columns), src.baseAddress, 1, gridPtr.baseAddress! + r*columns, 1)
}
}
}
}
/* Get or set multiple rows. */
public subscript(rows range: CountableRange<Int>) -> Matrix {
get {
precondition(range.upperBound <= rows, "Invalid range")
var m = Matrix.zeros(rows: range.upperBound - range.lowerBound, columns: columns)
for r in range {
for c in 0..<columns {
m[r - range.lowerBound, c] = self[r, c]
}
}
return m
}
set(m) {
precondition(range.upperBound <= rows, "Invalid range")
for r in range {
for c in 0..<columns {
self[r, c] = m[r - range.lowerBound, c]
}
}
}
}
public subscript(rows range: CountableClosedRange<Int>) -> Matrix {
get {
return self[rows: CountableRange(range)]
}
set(m) {
self[rows: CountableRange(range)] = m
}
}
/* Gets just the rows specified, in that order. */
public subscript(rows rowIndices: [Int]) -> Matrix {
var m = Matrix.zeros(rows: rowIndices.count, columns: columns)
/*
for (i, r) in rowIndices.enumerate() {
for c in 0..<columns {
m[i, c] = self[r, c]
}
}
*/
grid.withUnsafeBufferPointer { src in
m.grid.withUnsafeMutableBufferPointer { dst in
for (i, r) in rowIndices.enumerated() {
cblas_dcopy(Int32(columns), src.baseAddress! + r*columns, 1, dst.baseAddress! + i*columns, 1)
}
}
}
return m
}
/* Get or set an entire column. */
public subscript(column c: Int) -> Matrix {
get {
var v = Matrix.zeros(rows: rows, columns: 1)
/*
for r in 0..<rows {
m[r] = self[r, c]
}
*/
grid.withUnsafeBufferPointer { src in
v.grid.withUnsafeMutableBufferPointer { dst in
cblas_dcopy(Int32(rows), src.baseAddress! + c, Int32(columns), dst.baseAddress, 1)
}
}
return v
}
set(v) {
precondition(v.rows == rows && v.columns == 1, "Not a compatible column vector")
/*
for r in 0..<rows {
self[r, c] = v[r]
}
*/
v.grid.withUnsafeBufferPointer { src in
grid.withUnsafeMutableBufferPointer{ gridPtr in
cblas_dcopy(Int32(rows), src.baseAddress, 1, gridPtr.baseAddress! + c, Int32(columns))
}
}
}
}
/* Get or set multiple columns. */
public subscript(columns range: CountableRange<Int>) -> Matrix {
get {
precondition(range.upperBound <= columns, "Invalid range")
var m = Matrix.zeros(rows: rows, columns: range.upperBound - range.lowerBound)
for r in 0..<rows {
for c in range {
m[r, c - range.lowerBound] = self[r, c]
}
}
return m
}
set(m) {
precondition(range.upperBound <= columns, "Invalid range")
for r in 0..<rows {
for c in range {
self[r, c] = m[r, c - range.lowerBound]
}
}
}
}
public subscript(columns range: CountableClosedRange<Int>) -> Matrix {
get {
return self[columns: CountableRange(range)]
}
set(m) {
self[columns: CountableRange(range)] = m
}
}
/* Useful for when the matrix is 1x1 or you want to get the first element. */
public var scalar: Double {
return grid[0]
}
/* Converts the matrix into a 2-dimensional array. */
public var array: [[Double]] {
var a = [[Double]](repeating: [Double](repeating: 0, count: columns), count: rows)
for r in 0..<rows {
for c in 0..<columns {
a[r][c] = self[r, c]
}
}
return a
}
}
// MARK: - Printable
extension Matrix: CustomStringConvertible {
public var description: String {
var description = ""
for i in 0..<rows {
let contents = (0..<columns).map{ String(format: "%20.10f", self[i, $0]) }.joined(separator: " ")
switch (i, rows) {
case (0, 1):
description += "( \(contents) )\n"
case (0, _):
description += "⎛ \(contents) ⎞\n"
case (rows - 1, _):
description += "⎝ \(contents) ⎠\n"
default:
description += "⎜ \(contents) ⎥\n"
}
}
return description
}
}
// MARK: - SequenceType
/* Lets you iterate through the rows of the matrix. */
extension Matrix: Sequence {
public func makeIterator() -> AnyIterator<ArraySlice<Double>> {
let endIndex = rows * columns
var nextRowStartIndex = 0
return AnyIterator {
if nextRowStartIndex == endIndex {
return nil
} else {
let currentRowStartIndex = nextRowStartIndex
nextRowStartIndex += self.columns
return self.grid[currentRowStartIndex..<nextRowStartIndex]
}
}
}
}
// MARK: - Operations
extension Matrix {
public func inverse() -> Matrix {
precondition(rows == columns, "Matrix must be square")
var results = self
results.grid.withUnsafeMutableBufferPointer { ptr in
var ipiv = [__CLPK_integer](repeating: 0, count: rows * rows)
var lwork = __CLPK_integer(columns * columns)
var work = [CDouble](repeating: 0, count: Int(lwork))
var error: __CLPK_integer = 0
var nc = __CLPK_integer(columns)
var m = nc
var n = nc
dgetrf_(&m, &n, ptr.baseAddress, &nc, &ipiv, &error)
dgetri_(&m, ptr.baseAddress, &nc, &ipiv, &work, &lwork, &error)
assert(error == 0, "Matrix not invertible")
}
return results
}
}
extension Matrix {
public func transpose() -> Matrix {
var results = Matrix(rows: columns, columns: rows, repeatedValue: 0)
grid.withUnsafeBufferPointer { srcPtr in
vDSP_mtransD(srcPtr.baseAddress!, 1, &results.grid, 1, vDSP_Length(results.rows), vDSP_Length(results.columns))
}
return results
}
}
postfix operator ′
public postfix func ′ (value: Matrix) -> Matrix {
return value.transpose()
}
// MARK: - Arithmetic
/*
Element-by-element addition.
Either:
- both matrices have the same size
- rhs is a row vector with an equal number of columns as lhs
- rhs is a column vector with an equal number of rows as lhs
*/
public func + (lhs: Matrix, rhs: Matrix) -> Matrix {
if lhs.columns == rhs.columns {
if rhs.rows == 1 { // rhs is row vector
/*
var results = lhs
for r in 0..<results.rows {
for c in 0..<results.columns {
results[r, c] += rhs[0, c]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
lhs.grid.withUnsafeBufferPointer{ src in
results.grid.withUnsafeMutableBufferPointer{ dst in
for c in 0..<lhs.columns {
var v = rhs[c]
vDSP_vsaddD(src.baseAddress! + c, lhs.columns, &v, dst.baseAddress! + c, lhs.columns, vDSP_Length(lhs.rows))
}
}
}
return results
} else if lhs.rows == rhs.rows { // lhs and rhs are same size
var results = rhs
lhs.grid.withUnsafeBufferPointer { lhsPtr in
results.grid.withUnsafeMutableBufferPointer { resultsPtr in
cblas_daxpy(Int32(lhs.grid.count), 1, lhsPtr.baseAddress, 1, resultsPtr.baseAddress, 1)
}
}
return results
}
} else if lhs.rows == rhs.rows && rhs.columns == 1 { // rhs is column vector
/*
var results = lhs
for c in 0..<results.columns {
for r in 0..<results.rows {
results[r, c] += rhs[r, 0]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
lhs.grid.withUnsafeBufferPointer{ src in
results.grid.withUnsafeMutableBufferPointer{ dst in
for r in 0..<lhs.rows {
var v = rhs[r]
vDSP_vsaddD(src.baseAddress! + r*lhs.columns, 1, &v, dst.baseAddress! + r*lhs.columns, 1, vDSP_Length(lhs.columns))
}
}
}
return results
}
fatalError("Cannot add \(lhs.rows)×\(lhs.columns) matrix and \(rhs.rows)×\(rhs.columns) matrix")
}
public func += (lhs: inout Matrix, rhs: Matrix) {
lhs = lhs + rhs
}
/* Adds a scalar to each element of the matrix. */
public func + (lhs: Matrix, rhs: Double) -> Matrix {
/*
var m = lhs
for r in 0..<m.rows {
for c in 0..<m.columns {
m[r, c] += rhs
}
}
return m
*/
var results = lhs
lhs.grid.withUnsafeBufferPointer { src in
results.grid.withUnsafeMutableBufferPointer { dst in
var scalar = rhs
vDSP_vsaddD(src.baseAddress!, 1, &scalar, dst.baseAddress!, 1, vDSP_Length(lhs.rows * lhs.columns))
}
}
return results
}
public func += (lhs: inout Matrix, rhs: Double) {
lhs = lhs + rhs
}
/* Adds a scalar to each element of the matrix. */
public func + (lhs: Double, rhs: Matrix) -> Matrix {
return rhs + lhs
}
/*
Element-by-element subtraction.
Either:
- both matrices have the same size
- rhs is a row vector with an equal number of columns as lhs
- rhs is a column vector with an equal number of rows as lhs
*/
public func - (lhs: Matrix, rhs: Matrix) -> Matrix {
if lhs.columns == rhs.columns {
if rhs.rows == 1 { // rhs is row vector
/*
var results = lhs
for r in 0..<results.rows {
for c in 0..<results.columns {
results[r, c] -= rhs[0, c]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
lhs.grid.withUnsafeBufferPointer{ src in
results.grid.withUnsafeMutableBufferPointer{ dst in
for c in 0..<lhs.columns {
var v = -rhs[c]
vDSP_vsaddD(src.baseAddress! + c, lhs.columns, &v, dst.baseAddress! + c, lhs.columns, vDSP_Length(lhs.rows))
}
}
}
return results
} else if lhs.rows == rhs.rows { // lhs and rhs are same size
var results = lhs
rhs.grid.withUnsafeBufferPointer { rhsPtr in
results.grid.withUnsafeMutableBufferPointer { resultsPtr in
cblas_daxpy(Int32(rhs.grid.count), -1, rhsPtr.baseAddress, 1, resultsPtr.baseAddress, 1)
}
}
return results
}
} else if lhs.rows == rhs.rows && rhs.columns == 1 { // rhs is column vector
/*
var results = lhs
for c in 0..<results.columns {
for r in 0..<results.rows {
results[r, c] -= rhs[r, 0]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
lhs.grid.withUnsafeBufferPointer{ src in
results.grid.withUnsafeMutableBufferPointer{ dst in
for r in 0..<lhs.rows {
var v = -rhs[r]
vDSP_vsaddD(src.baseAddress! + r*lhs.columns, 1, &v, dst.baseAddress! + r*lhs.columns, 1, vDSP_Length(lhs.columns))
}
}
}
return results
}
fatalError("Cannot subtract \(lhs.rows)×\(lhs.columns) matrix and \(rhs.rows)×\(rhs.columns) matrix")
}
public func -= (lhs: inout Matrix, rhs: Matrix) {
lhs = lhs - rhs
}
/* Subtracts a scalar from each element of the matrix. */
public func - (lhs: Matrix, rhs: Double) -> Matrix {
return lhs + (-rhs)
}
public func -= (lhs: inout Matrix, rhs: Double) {
lhs = lhs - rhs
}
/* Subtracts each element of the matrix from a scalar. */
public func - (lhs: Double, rhs: Matrix) -> Matrix {
/*
var m = rhs
for r in 0..<m.rows {
for c in 0..<m.columns {
m[r, c] = lhs - rhs[r, c]
}
}
return m
*/
var results = rhs
var scalar = lhs
let length = vDSP_Length(rhs.rows * rhs.columns)
results.grid.withUnsafeMutableBufferPointer { ptr in
vDSP_vnegD(ptr.baseAddress!, 1, ptr.baseAddress!, 1, length)
vDSP_vsaddD(ptr.baseAddress!, 1, &scalar, ptr.baseAddress!, 1, length)
}
return results
}
/* Negates each element of the matrix. */
prefix public func -(m: Matrix) -> Matrix {
/*
var results = m
for r in 0..<m.rows {
for c in 0..<m.columns {
results[r, c] = -m[r, c]
}
}
return results
*/
var results = m
m.grid.withUnsafeBufferPointer { src in
results.grid.withUnsafeMutableBufferPointer { dst in
vDSP_vnegD(src.baseAddress!, 1, dst.baseAddress!, 1, vDSP_Length(m.rows * m.columns))
}
}
return results
}
infix operator <*> : MultiplicationPrecedence
/* Multiplies two matrices, or a matrix with a vector. */
public func <*> (lhs: Matrix, rhs: Matrix) -> Matrix {
precondition(lhs.columns == rhs.rows, "Cannot multiply \(lhs.rows)×\(lhs.columns) matrix and \(rhs.rows)×\(rhs.columns) matrix")
var results = Matrix(rows: lhs.rows, columns: rhs.columns, repeatedValue: 0)
lhs.grid.withUnsafeBufferPointer { lhsPtr in
rhs.grid.withUnsafeBufferPointer { rhsPtr in
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(lhs.rows), Int32(rhs.columns), Int32(lhs.columns), 1, lhsPtr.baseAddress, Int32(lhs.columns), rhsPtr.baseAddress, Int32(rhs.columns), 0, &results.grid, Int32(results.columns))
}
}
return results
}
/*
Multiplies each element of the lhs matrix by each element of the rhs matrix.
Either:
- both matrices have the same size
- rhs is a row vector with an equal number of columns as lhs
- rhs is a column vector with an equal number of rows as lhs
*/
public func * (lhs: Matrix, rhs: Matrix) -> Matrix {
if lhs.columns == rhs.columns {
if rhs.rows == 1 { // rhs is row vector
/*
var results = lhs
for r in 0..<results.rows {
for c in 0..<results.columns {
results[r, c] *= rhs[0, c]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
lhs.grid.withUnsafeBufferPointer{ src in
results.grid.withUnsafeMutableBufferPointer{ dst in
for c in 0..<lhs.columns {
var v = rhs[c]
vDSP_vsmulD(src.baseAddress! + c, lhs.columns, &v, dst.baseAddress! + c, lhs.columns, vDSP_Length(lhs.rows))
}
}
}
return results
} else if lhs.rows == rhs.rows { // lhs and rhs are same size
/*
var results = lhs
for r in 0..<results.rows {
for c in 0..<results.columns {
results[r, c] *= rhs[r, c]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
rhs.grid.withUnsafeBufferPointer{ srcX in
lhs.grid.withUnsafeBufferPointer{ srcY in
results.grid.withUnsafeMutableBufferPointer{ dstZ in
vDSP_vmulD(srcX.baseAddress!, 1, srcY.baseAddress!, 1, dstZ.baseAddress!, 1, vDSP_Length(lhs.rows * lhs.columns))
}
}
}
return results
}
} else if lhs.rows == rhs.rows && rhs.columns == 1 { // rhs is column vector
/*
var results = lhs
for c in 0..<results.columns {
for r in 0..<results.rows {
results[r, c] *= rhs[r, 0]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
lhs.grid.withUnsafeBufferPointer{ src in
results.grid.withUnsafeMutableBufferPointer{ dst in
for r in 0..<lhs.rows {
var v = rhs[r]
vDSP_vsmulD(src.baseAddress! + r*lhs.columns, 1, &v, dst.baseAddress! + r*lhs.columns, 1, vDSP_Length(lhs.columns))
}
}
}
return results
}
fatalError("Cannot element-wise multiply \(lhs.rows)×\(lhs.columns) matrix and \(rhs.rows)×\(rhs.columns) matrix")
}
/* Multiplies each element of the matrix with a scalar. */
public func * (lhs: Matrix, rhs: Double) -> Matrix {
var results = lhs
results.grid.withUnsafeMutableBufferPointer { ptr in
cblas_dscal(Int32(lhs.grid.count), rhs, ptr.baseAddress, 1)
}
return results
}
/* Multiplies each element of the matrix with a scalar. */
public func * (lhs: Double, rhs: Matrix) -> Matrix {
return rhs * lhs
}
infix operator </> : MultiplicationPrecedence
/* Divides a matrix by another. This is the same as multiplying with the inverse. */
public func </> (lhs: Matrix, rhs: Matrix) -> Matrix {
let inv = rhs.inverse()
precondition(lhs.columns == inv.rows, "Cannot divide \(lhs.rows)×\(lhs.columns) matrix and \(rhs.rows)×\(rhs.columns) matrix")
return lhs <*> inv
}
/*
Divides each element of the lhs matrix by each element of the rhs matrix.
Either:
- both matrices have the same size
- rhs is a row vector with an equal number of columns as lhs
- rhs is a column vector with an equal number of rows as lhs
*/
public func / (lhs: Matrix, rhs: Matrix) -> Matrix {
if lhs.columns == rhs.columns {
if rhs.rows == 1 { // rhs is row vector
/*
var results = lhs
for r in 0..<results.rows {
for c in 1..<results.columns {
results[r, c] /= rhs[0, c]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
lhs.grid.withUnsafeBufferPointer{ src in
results.grid.withUnsafeMutableBufferPointer{ dst in
for c in 0..<lhs.columns {
var v = rhs[c]
vDSP_vsdivD(src.baseAddress! + c, lhs.columns, &v, dst.baseAddress! + c, lhs.columns, vDSP_Length(lhs.rows))
}
}
}
return results
} else if lhs.rows == rhs.rows { // lhs and rhs are same size
/*
var results = lhs
for r in 0..<results.rows {
for c in 0..<results.columns {
results[r, c] /= rhs[r, c]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
rhs.grid.withUnsafeBufferPointer{ srcX in
lhs.grid.withUnsafeBufferPointer{ srcY in
results.grid.withUnsafeMutableBufferPointer{ dstZ in
vDSP_vdivD(srcX.baseAddress!, 1, srcY.baseAddress!, 1, dstZ.baseAddress!, 1, vDSP_Length(lhs.rows * lhs.columns))
}
}
}
return results
}
} else if lhs.rows == rhs.rows && rhs.columns == 1 { // rhs is column vector
/*
var results = lhs
for c in 0..<results.columns {
for r in 0..<results.rows {
results[r, c] /= rhs[r, 0]
}
}
return results
*/
var results = Matrix.zeros(size: lhs.size)
lhs.grid.withUnsafeBufferPointer{ src in
results.grid.withUnsafeMutableBufferPointer{ dst in
for r in 0..<lhs.rows {
var v = rhs[r]
vDSP_vsdivD(src.baseAddress! + r*lhs.columns, 1, &v, dst.baseAddress! + r*lhs.columns, 1, vDSP_Length(lhs.columns))
}
}
}
return results
}
fatalError("Cannot element-wise divide \(lhs.rows)×\(lhs.columns) matrix and \(rhs.rows)×\(rhs.columns) matrix")
}
/* Divides each element of the matrix by a scalar. */
public func / (lhs: Matrix, rhs: Double) -> Matrix {
var results = lhs
results.grid.withUnsafeMutableBufferPointer { ptr in
cblas_dscal(Int32(lhs.grid.count), 1/rhs, ptr.baseAddress, 1)
}
return results
}
/* Divides a scalar by each element of the matrix. */
public func / (lhs: Double, rhs: Matrix) -> Matrix {
/*
var m = rhs
for r in 0..<m.rows {
for c in 0..<m.columns {
m[r, c] = lhs / rhs[r, c]
}
}
return m
*/
var results = rhs
rhs.grid.withUnsafeBufferPointer { src in
results.grid.withUnsafeMutableBufferPointer { dst in
var scalar = lhs
vDSP_svdivD(&scalar, src.baseAddress!, 1, dst.baseAddress!, 1, vDSP_Length(rhs.rows * rhs.columns))
}
}
return results
}
// MARK: - Other maths
extension Matrix {
/* Exponentiates each element of the matrix. */
public func exp() -> Matrix {
/*
var result = m
for r in 0..<m.rows {
for c in 0..<m.columns {
result[r, c] = exp(m[r, c])
}
}
return result
*/
var result = self
grid.withUnsafeBufferPointer { src in
result.grid.withUnsafeMutableBufferPointer { dst in
var size = Int32(rows * columns)
vvexp(dst.baseAddress!, src.baseAddress!, &size)
}
}
return result
}
/* Takes the natural logarithm of each element of the matrix. */
public func log() -> Matrix {
/*
var result = m
for r in 0..<m.rows {
for c in 0..<m.columns {
result[r, c] = log(m[r, c])
}
}
return result
*/
var result = self
grid.withUnsafeBufferPointer { src in
result.grid.withUnsafeMutableBufferPointer { dst in
var size = Int32(rows * columns)