-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrix.cs
425 lines (336 loc) · 14.3 KB
/
Matrix.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lattice.Math
{
public static class Matrix
{
#region create
public static Matrix<T> Create<T>(T[,] values) => new Matrix<T>(values);
public static Matrix<T> Create<T>(int rows, int cols, Func<int, int, T> generator)
{
if (rows < 1 || cols < 1)
{
throw new ArgumentException("Dimensions must be greater than zero.");
}
var entries = new T[rows, cols];
for (var row = 0; row < rows; ++row)
{
for (var col = 0; col < cols; ++col)
{
entries[row, col] = generator(row, col);
}
}
return Create(entries);
}
public static Matrix<T> CreateZero<T>(int rows, int cols) => Create(rows, cols, (row, col) => LinearType<T>.Zero);
public static Matrix<T> CreateIdentity<T>(int rows, int cols) => Create(rows, cols, (row, col) => row == col ? LinearType<T>.One : LinearType<T>.Zero);
public static Matrix<T> CreateDiagonal<T>(Vector<T> vector) => Create(vector.Length, vector.Length, (row, col) => row == col ? vector[row] : LinearType<T>.Zero);
public static Matrix<T> CreateRows<T>(IEnumerable<Vector<T>> rows) => CreateRows(rows.Cast<IEnumerable<T>>());
public static Matrix<T> CreateColumns<T>(IEnumerable<Vector<T>> cols) => CreateColumns(cols.Cast<IEnumerable<T>>());
public static Matrix<T> CreateRows<T>(IEnumerable<IEnumerable<T>> rows)
{
if (rows.Count() < 1 || rows.First().Count() < 1)
{
throw new ArgumentException("Dimensions must be greater than zero.");
}
if (!rows.All(row => row.Count() == rows.First().Count()))
{
throw new ArgumentException("All rows must have the same length.");
}
var entries = new T[rows.Count(), rows.First().Count()];
foreach (var (row, values) in rows.Select((x, i) => (i, x)))
{
foreach (var (col, value) in values.Select((x, i) => (i, x)))
{
entries[row, col] = value;
}
}
return Create(entries);
}
public static Matrix<T> CreateColumns<T>(IEnumerable<IEnumerable<T>> cols)
{
if (cols.Count() < 1 || cols.First().Count() < 1)
{
throw new ArgumentException("Dimensions must be greater than zero.");
}
if (!cols.All(col => col.Count() == cols.First().Count()))
{
throw new ArgumentException("All rows must have the same length.");
}
var entries = new T[cols.First().Count(), cols.Count()];
foreach (var (col, values) in cols.Select((x, i) => (i, x)))
{
foreach (var (row, value) in values.Select((x, i) => (i, x)))
{
entries[row, col] = value;
}
}
return Create(entries);
}
#endregion
#region arithmetic
public static Matrix<T> AbsoluteValue<T>(Matrix<T> value)
{
return Create(value.Rows, value.Columns, (row, col) => LinearType<T>.AbsoluteValue(value[row, col]));
}
public static Matrix<T> Negate<T>(Matrix<T> value)
{
return Create(value.Rows, value.Columns, (row, col) => LinearType<T>.Negate(value[row, col]));
}
public static Matrix<T> Add<T>(Matrix<T> left, Matrix<T> right)
{
if (left.Rows != right.Rows || left.Columns != right.Columns)
{
throw new ArgumentException("Matrix dimensions must be equal.");
}
return Create(left.Rows, right.Columns, (row, col) => LinearType<T>.Add(left[row, col], right[row, col]));
}
public static Matrix<T> Subtract<T>(Matrix<T> left, Matrix<T> right)
{
if (left.Rows != right.Rows || left.Columns != right.Columns)
{
throw new ArgumentException("Matrix dimensions must be equal.");
}
return Create(left.Rows, right.Columns, (row, col) => LinearType<T>.Add(left[row, col], right[row, col]));
}
public static Matrix<T> Multiply<T>(Matrix<T> left, Matrix<T> right)
{
if (left.Columns != right.Rows)
{
throw new ArgumentException("Matrix dimensions must be compatible.");
}
return Create(left.Rows, right.Columns, (row, col) => Vector.InnerProduct(left.GetRow(row), right.GetColumn(col)));
}
public static Matrix<T> Multiply<T>(T left, Matrix<T> right)
{
return Create(right.Rows, right.Columns, (row, col) => LinearType<T>.Multiply(left, right[row, col]));
}
public static Matrix<T> Multiply<T>(Matrix<T> left, T right)
{
return Create(left.Rows, left.Columns, (row, col) => LinearType<T>.Multiply(left[row, col], right));
}
public static Vector<T> Multiply<T>(Vector<T> left, Matrix<T> right)
{
if (left.Length != right.Rows)
{
throw new ArgumentException("Vector and matrix dimensions must be compatible.");
}
return Vector.Create(right.Columns, col => Vector.InnerProduct(left, right.GetColumn(col)));
}
public static Vector<T> Multiply<T>(Matrix<T> left, Vector<T> right)
{
if (left.Columns != right.Length)
{
throw new ArgumentException("Matrix and vector dimensions must be compatible.");
}
return Vector.Create(left.Rows, row => Vector.InnerProduct(left.GetRow(row), right));
}
public static Matrix<T> Divide<T>(Matrix<T> left, T right)
{
return Create(left.Rows, left.Columns, (row, col) => LinearType<T>.Divide(left[row, col], right));
}
public static Matrix<T> Transpose<T>(Matrix<T> value)
{
return Create(value.Columns, value.Rows, (row, col) => value[col, row]);
}
public static Matrix<T> RowReduce<T>(Matrix<T> value, out int rank, int count = -1)
{
if (count == -1)
{
count = value.Columns;
}
var rows = value.GetRows().ToArray();
var map = new int[count];
rank = 0;
for (var col = 0; col < count && rank < value.Rows; ++col)
{
var bestRow = rank;
for (var row = rank + 1; row < value.Rows; ++row)
{
if (LinearType<T>.Compare(LinearType<T>.AbsoluteValue(rows[row][col]), LinearType<T>.AbsoluteValue(rows[bestRow][col])) > 0)
{
bestRow = row;
}
}
if (LinearType<T>.IsZero(rows[bestRow][col]))
{
map[col] = -1;
continue;
}
(rows[rank], rows[bestRow]) = (rows[bestRow], rows[rank]);
rows[rank] = Vector.Divide(rows[rank], rows[rank][col]);
for (var row = rank + 1; row < value.Rows; ++row)
{
rows[row] -= Vector.Multiply(rows[rank], rows[row][col]);
}
map[col] = rank;
++rank;
}
for (var col = count - 1; col >= 0; --col)
{
for (var row = map[col] - 1; row >= 0; --row)
{
rows[row] -= Vector.Multiply(rows[map[col]], rows[row][col]);
}
}
return Create(value.Rows, value.Columns, (row, col) => rows[row][col]);
}
public static Matrix<T> RowReduce<T>(Matrix<T> value, int count = -1)
{
var rank = 0;
var result = RowReduce(value, out rank, count);
return result;
}
public static Matrix<T> Inverse<T>(Matrix<T> value)
{
if (value.Rows != value.Columns)
{
throw new ArgumentException("Matrix must be square.");
}
var identity = CreateIdentity<T>(value.Rows, value.Columns);
var intermediate = Create(value.Rows, 2 * value.Columns, (row, col) => col < value.Columns ? value[row, col] : identity[row, col - value.Columns]);
var rank = 0;
var result = RowReduce(intermediate, out rank, value.Columns);
if (rank != value.Rows)
{
throw new ArithmeticException("Matrix must be invertible.");
}
return Create(value.Rows, value.Columns, (row, col) => result[row, value.Columns + col]);
}
#endregion
}
public readonly struct Matrix<T>
{
#region op_arithmetic
public static Matrix<T> operator +(Matrix<T> value) => value;
public static Matrix<T> operator -(Matrix<T> value) => Matrix.Negate(value);
public static Matrix<T> operator +(Matrix<T> left, Matrix<T> right) => Matrix.Add(left, right);
public static Matrix<T> operator -(Matrix<T> left, Matrix<T> right) => Matrix.Subtract(left, right);
public static Matrix<T> operator *(Matrix<T> left, Matrix<T> right) => Matrix.Multiply(left, right);
public static Matrix<T> operator *(T left, Matrix<T> right) => Matrix.Multiply(left, right);
public static Matrix<T> operator *(Matrix<T> left, T right) => Matrix.Multiply(left, right);
public static Vector<T> operator *(Vector<T> left, Matrix<T> right) => Matrix.Multiply(left, right);
public static Vector<T> operator *(Matrix<T> left, Vector<T> right) => Matrix.Multiply(left, right);
public static Matrix<T> operator /(Matrix<T> left, T right) => Matrix.Divide(left, right);
#endregion
#region op_compare
public static bool operator ==(Matrix<T> left, Matrix<T> right) => left.Equals(right);
public static bool operator !=(Matrix<T> left, Matrix<T> right) => !left.Equals(right);
#endregion
public readonly int Rows { get => values.GetLength(0); }
public readonly int Columns { get => values.GetLength(1); }
private readonly T[,] values;
internal Matrix(T[,] values)
{
this.values = new T[values.GetLength(0), values.GetLength(1)];
Array.Copy(values, this.values, values.Length);
}
public IEnumerable<Vector<T>> GetRows()
{
var values = this.values;
var rows = this.Rows;
var cols = this.Columns;
return Enumerable.Range(0, rows).Select(row => Vector.Create(cols, col => values[row, col]));
}
public IEnumerable<Vector<T>> GetColumns()
{
var values = this.values;
var rows = this.Rows;
var cols = this.Columns;
return Enumerable.Range(0, cols).Select(col => Vector.Create(rows, row => values[row, col]));
}
public Vector<T> GetRow(int row)
{
var values = this.values;
return Vector.Create(this.Columns, col => values[row, col]);
}
public Vector<T> GetColumn(int col)
{
var values = this.values;
return Vector.Create(this.Rows, row => values[row, col]);
}
public Matrix<T> GetTranspose() => Matrix.Transpose(this);
public Matrix<T> GetInverse() => Matrix.Inverse(this);
public Matrix<T> GetRowReduce(out int rank, int count = -1) => Matrix.RowReduce(this, out rank, count);
public Matrix<T> GetRowReduce(int count = -1) => Matrix.RowReduce(this, count);
public readonly T this[int row, int col] { get => this.values[row, col]; }
public bool Equals(Matrix<T> other)
{
if (this.Rows != other.Rows || this.Columns != other.Columns)
{
return false;
}
for (var row = 0; row < this.Rows; ++row)
{
for (var col = 0; col < this.Columns; ++col)
{
if (LinearType<T>.Compare(this[row, col], other[row, col]) != 0)
{
return false;
}
}
}
return true;
}
public override bool Equals(object other)
{
if (other is Matrix<T> matrix)
{
return this.Equals(matrix);
}
else
{
return false;
}
}
public override int GetHashCode()
{
var hash = 0;
for (var row = 0; row < this.Rows; ++row)
{
for (var col = 0; col < this.Columns; ++col)
{
hash = (hash, this[row, col]).GetHashCode();
}
}
return hash;
}
public override string ToString()
{
var strings = new string[this.Rows, this.Columns];
var lengths = new int[this.Columns];
for (var row = 0; row < this.Rows; ++row)
{
for (var col = 0; col < this.Columns; ++col)
{
strings[row, col] = this[row, col].ToString();
if (strings[row, col].Length > lengths[col])
{
lengths[col] = strings[row, col].Length;
}
}
}
// [[x, x]]
var result = new StringBuilder();
for (var row = 0; row < this.Rows; ++row)
{
for (var col = 0; col < this.Columns; ++col)
{
result.Append(col == 0 ? row == 0 ? "[[" : " [" : ", ");
result.Append(' ', lengths[col] - strings[row, col].Length);
result.Append(strings[row, col]);
}
result.Append(row == this.Rows - 1 ? "]]" : "]\n");
}
return result.ToString();
}
public T[,] ToArray()
{
var values = new T[this.Rows, this.Columns];
Array.Copy(this.values, values, this.values.Length);
return values;
}
}
}