-
Notifications
You must be signed in to change notification settings - Fork 1
/
Matrix.cs
356 lines (326 loc) · 12.4 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
using System;
using System.Linq;
using System.Runtime.CompilerServices;
namespace JA
{
public record Matrix(double[][] Elements) : IQuantity
{
public static readonly Matrix Empty = Array.Empty<double[]>();
public static implicit operator Matrix(double[][] matrix) => new(matrix);
public static implicit operator double[][](Matrix matrix) => matrix.Elements;
#region Factory
public Matrix(Vector[] matrix) :
this(matrix.Select(row => row.Elements).ToArray())
{ }
public Matrix(int rows, int columns)
: this(CreateJagged(rows, columns))
{ }
public Matrix(int rows, int columns, Func<int, int, double> initializer)
: this(CreateJagged(rows, columns, initializer))
{ }
static double[][] CreateJagged(int rows, int columns, Func<int, int, double> initializer = null)
{
var result = new double[rows][];
for (int i = 0; i < rows; i++)
{
var row = new double[columns];
if (initializer!=null)
{
for (int j = 0; j < row.Length; j++)
{
row[j] = initializer(i, j);
}
}
result[i] = row;
}
return result;
}
public static Matrix Block(Matrix A, Vector b, Vector c, double d)
{
var result = CreateJagged(A.Rows+1, A.Columns+1);
for (int i = 0; i < A.Rows; i++)
{
Array.Copy(A.Elements[i], result[i], A.Columns);
result[i][^1] = b.Elements[i];
}
Array.Copy(c.Elements, result[^0], A.Columns);
result[^1][^1] = d;
return new Matrix(result);
}
public bool GetBlock(out Matrix A, out Vector b, out Vector c, out double d)
{
if (Rows>1 && Columns>1)
{
A = this[..^1, ..^1];
b = this[..^1, ^1];
c = this[^1, ..^1];
d = this[^1, ^1];
return true;
}
A = null;
b = null;
c = null;
d = 0;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix Zeros(int rows, int columns)
{
return new Matrix(rows, columns);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix Identity(int size) => Diagonal(size, 1.0);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix Diagonal(int size, double value)
=> new(CreateJagged(size, size, (i, j) => i==j ? value : 0));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix Diagonal(Vector vector)
=> new(CreateJagged(vector.Size, vector.Size, (i, j) => i==j ? vector[i] : 0));
#endregion
public int Rank { get => 2; }
public int Rows { get => Elements.Length; }
public int Columns { get => Elements.Length>0 ? Elements[0].Length : 0; }
double IQuantity.Value { get => 0; }
double[] IQuantity.Array { get => null; }
double[][] IQuantity.Array2 { get => Elements; }
/// <summary>
/// Reference an element of the matrix
/// </summary>
/// <param name="row">The row index.</param>
/// <param name="column">The column index.</param>
public ref double this[Index row, Index column]
=> ref Elements[row][column];
/// <summary>
/// Extract a sub-matrix.
/// </summary>
/// <param name="rows">The range of rows.</param>
/// <param name="columns">The range of columns.</param>
public double[][] this[Range rows, Range columns]
{
get
{
var slice = Elements[rows];
for (int i = 0; i < slice.Length; i++)
{
slice[i] = slice[i][columns];
}
return slice;
}
}
/// <summary>
/// Extract a row sub-vector.
/// </summary>
/// <param name="row">The row index.</param>
/// <param name="columns">The range of columns.</param>
public double[] this[Index row, Range columns]
{
get
{
var slice = Elements[row];
var result = slice[columns];
return result;
}
}
/// <summary>
/// Extract a column sub-vector.
/// </summary>
/// <param name="rows">The range of rows.</param>
/// <param name="column">The column index.</param>
public double[] this[Range rows, Index column]
{
get
{
var slice = Elements[rows];
var result = new double[slice.Length];
for (int i = 0; i < slice.Length; i++)
{
result[i] = slice[i][column];
}
return result;
}
}
public ReadOnlySpan<double[]> AsSpan() => AsSpan(Range.All);
public ReadOnlySpan<double[]> AsSpan(Range rows)
{
var (offset, length)= rows.GetOffsetAndLength(Elements.Length);
return new ReadOnlySpan<double[]>(Elements, offset, length);
}
#region Formatting
public override string ToString() => ToString("g");
public string ToString(string formatting) => ToString(formatting, null);
public string ToString(string formatting, IFormatProvider formatProvider)
=> $"[{string.Join(",", Elements.Select(row => ((Vector)row).ToString(formatting, formatProvider)))}]";
#endregion
#region Algebra
public static Matrix Add(Matrix A, Matrix B)
{
var result = new double[A.Rows][];
for (int i = 0; i < result.Length; i++)
{
var row = new double[A.Columns];
var Arow = A.Elements[i];
var Brow = B.Elements[i];
for (int j = 0; j < row.Length; j++)
{
row[j] = Arow[j] + Brow[j];
}
result[i] = row;
}
return new Matrix(result);
}
public static Matrix Subtract(Matrix A, Matrix B)
{
var result = new double[A.Rows][];
for (int i = 0; i < result.Length; i++)
{
var row = new double[A.Columns];
var Arow = A.Elements[i];
var Brow = B.Elements[i];
for (int j = 0; j < row.Length; j++)
{
row[j] = Arow[j] - Brow[j];
}
result[i] = row;
}
return new Matrix(result);
}
public static Matrix Scale(double factor, Matrix A)
{
var result = new double[A.Rows][];
for (int i = 0; i < result.Length; i++)
{
var row = new double[A.Columns];
var Arow = A.Elements[i];
for (int j = 0; j < row.Length; j++)
{
row[j] = factor * Arow[j];
}
result[i] = row;
}
return new Matrix(result);
}
public static Vector Product(Vector a, Matrix B) => Product(B.Transpose(), a);
public static Vector Product(Matrix A, Vector b)
{
var result = new double[A.Rows];
for (int i = 0; i < result.Length; i++)
{
double sum = 0;
var Arow = A.Elements[i];
for (int k = 0; k < b.Elements.Length; k++)
{
sum += Arow[k] * b.Elements[k];
}
result[i] = sum;
}
return new Vector(result);
}
public static Matrix Product(Matrix A, Matrix B)
{
var result = new double[A.Rows][];
for (int i = 0; i < result.Length; i++)
{
var row = new double[B.Columns];
var Arow = A.Elements[i];
for (int j = 0; j < row.Length; j++)
{
double sum = 0;
for (int k = 0; k < Arow.Length; k++)
{
sum += Arow[k] * B.Elements[k][j];
}
row[j] = sum;
}
result[i] = row;
}
return new Matrix(result);
}
public Matrix Transpose()
{
int n = Rows;
int m = Columns;
var result = new double[m][];
for (int i = 0; i < result.Length; i++)
{
var row = new double[n];
for (int j = 0; j < row.Length; j++)
{
row[j] = Elements[j][i];
}
result[i] = row;
}
return result;
}
public Matrix Inverse() => Solve(Identity(Rows));
public Vector Solve(Vector vector)
{
if (Rows != vector.Size)
{
throw new ArgumentOutOfRangeException(nameof(vector), "Mismatch between matrix rows and vector size.");
}
if (Rows==1 && Columns==1 && vector.Size==1)
{
return new Vector(vector.Elements[0]/ Elements[0][0]);
}
if (GetBlock(out var A, out var b, out var c, out var d))
{
if (vector.GetBlock(out var u, out var y))
{
var Au = A.Solve(u);
var Ab = A.Solve(b);
double x = (y - Vector.Dot(c, Au))/(d - Vector.Dot(c,Ab));
Vector v = Au - x*Ab;
var result = new double[Rows];
Array.Copy(v.Elements, result, result.Length-1);
result[^1] = x;
return result;
}
}
throw new ArgumentException("Invalid inputs.", nameof(vector));
}
public Matrix Solve(Matrix matrix)
{
if (Rows != matrix.Rows)
{
throw new ArgumentOutOfRangeException(nameof(matrix), "Mismatch between matrix rows.");
}
if (Rows==1 && Columns==1 && matrix.Rows==1 && matrix.Columns==1)
{
var result = CreateJagged(1,1);
result[0][0] = matrix.Elements[0][0]/this.Elements[0][0];
return new Matrix(result);
}
if (GetBlock(out var A, out var b, out var c, out var d))
{
if (matrix.GetBlock(out var U, out var u, out var h, out var y))
{
var Au = A.Solve(u);
var Ab = A.Solve(b);
double x = (y - Vector.Dot(c, Au))/(d - Vector.Dot(c,Ab));
Matrix Abc = A - Vector.Outer(b, c);
Matrix V = Abc.Solve(d*U - Vector.Outer(b,h));
Vector v = A.Solve( u - x*b);
Vector g = (h - c*V)/d;
return Block(V, v, g, x);
}
}
throw new ArgumentException("Invalid inputs.", nameof(matrix));
}
#endregion
#region Operators
public static Matrix operator +(Matrix A, Matrix B) => Add(A, B);
public static Matrix operator -(Matrix A, Matrix B) => Subtract(A, B);
public static Matrix operator -(Matrix A) => Scale(-1, A);
public static Matrix operator *(double factor, Matrix B) => Scale(factor, B);
public static Matrix operator *(Matrix A, double factor) => Scale(factor, A);
public static Vector operator *(Matrix A, Vector b) => Product(A, b);
public static Matrix operator *(Matrix A, Matrix B) => Product(A, B);
public static Vector operator *(Vector a, Matrix B) => Product(a, B);
public static Matrix operator /(Matrix A, double divisor) => Scale(1/divisor, A);
public static Matrix operator ~(Matrix A) => A.Transpose();
public static Matrix operator !(Matrix A) => A.Inverse();
public static Vector operator /(Vector b, Matrix A) => A.Solve(b);
public static Matrix operator /(Matrix B, Matrix A) => A.Solve(B);
#endregion
}
}