This repository was archived by the owner on Nov 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathMatrix.Common.cs
More file actions
2155 lines (1874 loc) · 74.8 KB
/
Copy pathMatrix.Common.cs
File metadata and controls
2155 lines (1874 loc) · 74.8 KB
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
// Accord Math Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2017
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Math
{
using System;
using Accord.Math.Decompositions;
using Accord.Math.Comparers;
using System.Collections.Generic;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Runtime.InteropServices;
/// <summary>
/// Special matrix types.
/// </summary>
///
/// <seealso cref="VectorType"/>
///
[Flags]
public enum MatrixType
{
/// <summary>
/// Symmetric matrix.
/// </summary>
///
Symmetric,
/// <summary>
/// Lower (left) triangular matrix.
/// </summary>
///
LowerTriangular,
/// <summary>
/// Upper (right) triangular matrix.
/// </summary>
///
UpperTriangular,
/// <summary>
/// Diagonal matrix.
/// </summary>
///
Diagonal,
/// <summary>
/// Rectangular matrix.
/// </summary>
///
Rectangular,
/// <summary>
/// Square matrix.
/// </summary>
///
Square,
}
public static partial class Matrix
{
/// <summary>
/// Determines whether the specified type is a jagged array.
/// </summary>
///
public static bool IsJagged(this Type type)
{
return type.IsArray && type.GetElementType().IsArray;
}
/// <summary>
/// Gets the type of the element in a jagged or multi-dimensional matrix.
/// </summary>
///
/// <param name="array">The array whose element type should be computed.</param>
///
public static Type GetInnerMostType(this Array array)
{
Type type = array.GetType();
while (type.IsArray)
type = type.GetElementType();
return type;
}
#region Comparison
/// <summary>
/// Determines whether a number is an integer, given a tolerance threshold.
/// </summary>
///
/// <param name="x">The value to be compared.</param>
/// <param name="threshold">The maximum that the number can deviate from its closest integer number.</param>
///
/// <returns>True if the number if an integer, false otherwise.</returns>
///
public static bool IsInteger(this double x, double threshold = Constants.DoubleSmall)
{
double a = Math.Round(x);
double b = x;
if (a == b)
return true;
double limit = Math.Abs(a) * threshold;
double delta = Math.Abs(a - b);
return delta <= limit;
}
/// <summary>
/// Compares two values for equality, considering a relative acceptance threshold.
/// </summary>
///
#if NET45 || NET46 || NET462 || NETSTANDARD2_0
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
[Obsolete("Use IsEqual(a, b, rtol) with the named parameter rtol instead.")]
public static bool IsRelativelyEqual(this double a, double b, double threshold)
{
return a.IsEqual(b, rtol: threshold);
}
/// <summary>
/// Compares two objects for equality, performing an elementwise
/// comparison if the elements are vectors or matrices.
/// </summary>
///
public static bool IsEqual(this object objA, object objB, decimal atol = 0, decimal rtol = 0)
{
if (Object.Equals(objA, objB))
return true;
#if !NETSTANDARD1_4
if (objA is DBNull)
objA = null;
if (objB is DBNull)
objB = null;
#endif
if (objA == null ^ objB == null)
return false;
try
{
decimal a = System.Convert.ToDecimal(objA);
decimal b = System.Convert.ToDecimal(objB);
if (a == b)
return true;
if (atol > 0)
return Math.Abs(a - b) < atol;
if (rtol > 0)
return Math.Abs(a - b) < rtol * b;
}
catch { } // TODO: Remove this try-catch block
return false;
}
/// <summary>
/// Compares two matrices for equality.
/// </summary>
///
public static bool IsEqual(this Array objA, Array objB, double atol = 0, double rtol = 0)
{
if (objA == objB)
return true;
if (objA == null)
throw new ArgumentNullException("objA");
if (objB == null)
throw new ArgumentNullException("objB");
if (!objA.GetLength().IsEqual(objB.GetLength()))
return false;
bool jaggedA = objA.IsJagged();
bool jaggedB = objB.IsJagged();
// TODO: Implement this cache mechanism here
// http://blog.slaks.net/2015-06-26/code-snippets-fast-property-access-reflection/
// Check if there is already an optimized method to perform this comparison
Type typeA = objA.GetType();
Type typeB = objB.GetType();
#if !NETSTANDARD1_4
MethodInfo equals = typeof(Matrix).GetMethod("IsEqual", new Type[] {
typeA, typeB, typeof(double), typeof(double)
});
MethodInfo _this = typeof(Matrix).GetMethod("IsEqual", new Type[] {
typeof(Array), typeof(Array), typeof(double), typeof(double)
});
if (equals != _this)
return (bool)equals.Invoke(null, new object[] { objA, objB, atol, rtol });
#endif
// Base case: arrays contain elements of same nature (both arrays, or both values)
if (objA.GetType().GetElementType().IsArray == objB.GetType().GetElementType().IsArray)
{
var a = objA.GetEnumerator();
var b = objB.GetEnumerator();
while (a.MoveNext() && b.MoveNext())
{
if (a.Current == b.Current)
continue;
Array arrA = a.Current as Array;
Array arrB = b.Current as Array;
if (arrA != null && arrB != null && IsEqual(arrA, arrB, atol, rtol))
continue;
if (!IsEqual(a.Current, b.Current, (decimal)atol, (decimal)rtol))
return false;
}
return true;
}
else
{
// Arrays contain mixed elements (i.e. one is jagged and other multidimensional)
foreach (int[] idx in Matrix.GetIndices(objA, deep: true, max: true))
{
object a = 0, b = 0;
objA.TryGetValue(deep: true, indices: idx, value: out a);
objB.TryGetValue(deep: true, indices: idx, value: out b);
if (!IsEqual(a, b, (decimal)atol, (decimal)rtol))
return false;
}
return true;
}
}
/// <summary>
/// This method should not be called. Use Matrix.IsEqual instead.
/// </summary>
///
public static new bool Equals(object value)
{
throw new NotSupportedException("Use Matrix.IsEqual instead.");
}
/// <summary>
/// Checks whether two arrays have the same dimensions.
/// </summary>
///
public static bool DimensionEquals(this Array a, Array b)
{
if (a.Rank != b.Rank)
return false;
for (int i = 0; i < a.Rank; i++)
if (a.GetLength(i) != b.GetLength(i))
return false;
return true;
}
/// <summary>
/// Compares two enumerables for set equality. Two
/// enumerables are set equal if they contain the
/// same elements, but not necessarily in the same
/// order.
/// </summary>
///
/// <typeparam name="T">The element type.</typeparam>
///
/// <param name="list1">The first set.</param>
/// <param name="list2">The first set.</param>
///
/// <returns>
/// True if the two sets contains the same elements, false otherwise.
/// </returns>
///
public static bool SetEquals<T>(this IEnumerable<T> list1, IEnumerable<T> list2)
{
var cnt = new Dictionary<T, int>();
foreach (var s in list1)
{
if (cnt.ContainsKey(s))
cnt[s]++;
else cnt.Add(s, 1);
}
foreach (var s in list2)
{
if (cnt.ContainsKey(s))
cnt[s]--;
else return false;
}
foreach (var s in cnt)
{
if (s.Value != 0)
return false;
}
return true;
}
/// <summary>
/// Returns a value indicating whether the specified
/// matrix contains a value that is not a number (NaN).
/// </summary>
///
/// <param name="matrix">A double-precision multidimensional matrix.</param>
///
/// <returns>True if the matrix contains a value that is not a number, false otherwise.</returns>
///
public static bool HasNaN(this double[,] matrix)
{
foreach (var e in matrix)
if (Double.IsNaN(e)) return true;
return false;
}
/// <summary>
/// Returns a value indicating whether the specified
/// matrix contains a value that is not a number (NaN).
/// </summary>
///
/// <param name="matrix">A double-precision multidimensional matrix.</param>
///
/// <returns>True if the matrix contains a value that is not a number, false otherwise.</returns>
///
public static bool HasNaN(this double[] matrix)
{
foreach (var e in matrix)
if (Double.IsNaN(e))
return true;
return false;
}
/// <summary>
/// Returns a value indicating whether the specified
/// matrix contains a value that is not a number (NaN).
/// </summary>
///
/// <param name="matrix">A double-precision multidimensional matrix.</param>
///
/// <returns>True if the matrix contains a value that is not a number, false otherwise.</returns>
///
public static bool HasNaN(this double[][] matrix)
{
for (int i = 0; i < matrix.Length; i++)
for (int j = 0; j < matrix[i].Length; j++)
if (Double.IsNaN(matrix[i][j]))
return true;
return false;
}
/// <summary>
/// Returns a value indicating whether the specified
/// matrix contains a infinity value.
/// </summary>
///
/// <param name="matrix">A double-precision multidimensional matrix.</param>
///
/// <returns>True if the matrix contains infinity values, false otherwise.</returns>
///
public static bool HasInfinity(this double[,] matrix)
{
foreach (var e in matrix)
if (Double.IsInfinity(e))
return true;
return false;
}
/// <summary>
/// Returns a value indicating whether the specified
/// matrix contains a value within a given tolerance.
/// </summary>
///
/// <param name="matrix">A double-precision multidimensional matrix.</param>
/// <param name="value">The value to search for in the matrix.</param>
/// <param name="tolerance">The relative tolerance that a value must be in
/// order to be considered equal to the value being searched.</param>
///
/// <returns>True if the matrix contains the value, false otherwise.</returns>
///
public static bool Has(this double[,] matrix, double value, double tolerance = 0.0)
{
foreach (var e in matrix)
if (Math.Abs(e - value) <= Math.Abs(e) * tolerance)
return true;
return false;
}
/// <summary>
/// Returns a value indicating whether the specified
/// matrix contains a value within a given tolerance.
/// </summary>
///
/// <param name="matrix">A single-precision multidimensional matrix.</param>
/// <param name="value">The value to search for in the matrix.</param>
/// <param name="tolerance">The relative tolerance that a value must be in
/// order to be considered equal to the value being searched.</param>
///
/// <returns>True if the matrix contains the value, false otherwise.</returns>
///
public static bool Has(this float[,] matrix, float value, double tolerance = 0.0)
{
foreach (var e in matrix)
if (Math.Abs(e - value) <= Math.Abs(e) * tolerance)
return true;
return false;
}
/// <summary>
/// Returns a value indicating whether the specified
/// matrix contains a infinity value.
/// </summary>
///
/// <param name="matrix">A double-precision multidimensional matrix.</param>
///
/// <returns>True if the matrix contains a infinity value, false otherwise.</returns>
///
public static bool HasInfinity(this double[] matrix)
{
foreach (var e in matrix)
if (Double.IsInfinity(e))
return true;
return false;
}
/// <summary>
/// Returns a value indicating whether the specified
/// matrix contains a infinity value.
/// </summary>
///
/// <param name="matrix">A double-precision multidimensional matrix.</param>
///
/// <returns>True if the matrix contains a infinity value, false otherwise.</returns>
///
public static bool HasInfinity(this double[][] matrix)
{
for (int i = 0; i < matrix.Length; i++)
for (int j = 0; j < matrix[i].Length; j++)
if (Double.IsInfinity(matrix[i][j]))
return true;
return false;
}
#endregion
#region Transpose
/// <summary>
/// Gets the transpose of a matrix.
/// </summary>
///
/// <param name="matrix">A matrix.</param>
///
/// <returns>The transpose of the given matrix.</returns>
///
public static T[,] Transpose<T>(this T[,] matrix)
{
return Transpose(matrix, false);
}
/// <summary>
/// Gets the transpose of a matrix.
/// </summary>
///
/// <param name="matrix">A matrix.</param>
///
/// <param name="inPlace">True to store the transpose over the same input
/// <paramref name="matrix"/>, false otherwise. Default is false.</param>
///
/// <returns>The transpose of the given matrix.</returns>
///
public static T[,] Transpose<T>(this T[,] matrix, bool inPlace)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
if (inPlace)
{
if (rows != cols)
throw new ArgumentException("Only square matrices can be transposed in place.", "matrix");
#if DEBUG
T[,] expected = matrix.Transpose();
#endif
for (int i = 0; i < rows; i++)
{
for (int j = i; j < cols; j++)
{
T element = matrix[j, i];
matrix[j, i] = matrix[i, j];
matrix[i, j] = element;
}
}
#if DEBUG
if (!expected.IsEqual(matrix))
throw new Exception();
#endif
return matrix;
}
else
{
T[,] result = new T[cols, rows];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
result[j, i] = matrix[i, j];
return result;
}
}
/// <summary>
/// Gets the transpose of a row vector.
/// </summary>
///
/// <param name="rowVector">A row vector.</param>
///
/// <returns>The transpose of the given vector.</returns>
///
public static T[,] Transpose<T>(this T[] rowVector)
{
var result = new T[rowVector.Length, 1];
for (int i = 0; i < rowVector.Length; i++)
result[i, 0] = rowVector[i];
return result;
}
/// <summary>
/// Gets the transpose of a row vector.
/// </summary>
///
/// <param name="rowVector">A row vector.</param>
/// <param name="result">The matrix where to store the transpose.</param>
///
/// <returns>The transpose of the given vector.</returns>
///
public static T[,] Transpose<T>(this T[] rowVector, T[,] result)
{
for (int i = 0; i < rowVector.Length; i++)
result[i, 0] = rowVector[i];
return result;
}
/// <summary>
/// Gets the generalized transpose of a tensor.
/// </summary>
///
/// <param name="array">A tensor.</param>
/// <param name="order">The new order for the tensor's dimensions.</param>
///
/// <returns>The transpose of the given tensor.</returns>
///
public static Array Transpose(this Array array, int[] order)
{
return transpose(array, order);
}
/// <summary>
/// Gets the generalized transpose of a tensor.
/// </summary>
///
/// <param name="array">A tensor.</param>
/// <param name="order">The new order for the tensor's dimensions.</param>
///
/// <returns>The transpose of the given tensor.</returns>
///
public static T Transpose<T>(this T array, int[] order)
where T : class, IList
{
Array arr = array as Array;
if (arr == null)
throw new ArgumentException("The given object must inherit from System.Array.", "array");
return transpose(arr, order) as T;
}
private static Array transpose(Array array, int[] order)
{
if (array.Length == 1 || array.Length == 0)
return array;
// Get the number of samples at each dimension
int[] size = new int[array.Rank];
for (int i = 0; i < size.Length; i++)
size[i] = array.GetLength(i);
Array r = Array.CreateInstance(array.GetType().GetElementType(), size.Get(order));
// Generate all indices for accessing the matrix
foreach (int[] pos in Combinatorics.Sequences(size, true))
{
int[] newPos = pos.Get(order);
object value = array.GetValue(pos);
r.SetValue(value, newPos);
}
return r;
}
#endregion
#region Matrix Characteristics
/// <summary>
/// Gets the total number of elements in the vector.
/// </summary>
///
public static int GetNumberOfElements<T>(this T[] value)
{
return value.Length;
}
/// <summary>
/// Gets the total number of elements in the matrix.
/// </summary>
///
public static int GetNumberOfElements<T>(this T[][] value)
{
int sum = 0;
for (int i = 0; i < value.Length; i++)
sum += value[i].Length;
return sum;
}
/// <summary>
/// Gets the total number of elements in the matrix.
/// </summary>
///
public static int GetNumberOfElements<T>(this T[,] elements)
{
return elements.GetLength().Product();
}
/// <summary>
/// Gets the size of a vector, in bytes.
/// </summary>
///
public static int GetSizeInBytes<T>(this T[] elements)
{
#if NETSTANDARD1_4
return elements.GetNumberOfElements() * Marshal.SizeOf<T>();
#else
return elements.GetNumberOfElements() * Marshal.SizeOf(typeof(T));
#endif
}
/// <summary>
/// Gets the size of a matrix, in bytes.
/// </summary>
///
public static int GetSizeInBytes<T>(this T[][] elements)
{
#if NETSTANDARD1_4
return elements.GetNumberOfElements() * Marshal.SizeOf<T>();
#else
return elements.GetNumberOfElements() * Marshal.SizeOf(typeof(T));
#endif
}
/// <summary>
/// Gets the size of a matrix, in bytes.
/// </summary>
///
public static int GetSizeInBytes<T>(this T[,] elements)
{
#if NETSTANDARD1_4
return elements.GetNumberOfElements() * Marshal.SizeOf<T>();
#else
return elements.GetNumberOfElements() * Marshal.SizeOf(typeof(T));
#endif
}
/// <summary>
/// Gets the number of rows in a vector.
/// </summary>
///
/// <typeparam name="T">The type of the elements in the column vector.</typeparam>
/// <param name="vector">The vector whose number of rows must be computed.</param>
///
/// <returns>The number of rows in the column vector.</returns>
///
public static int Rows<T>(this T[] vector)
{
return vector.Length;
}
/// <summary>
/// Gets the number of rows in a multidimensional matrix.
/// </summary>
///
/// <typeparam name="T">The type of the elements in the matrix.</typeparam>
/// <param name="matrix">The matrix whose number of rows must be computed.</param>
///
/// <returns>The number of rows in the matrix.</returns>
///
public static int Rows<T>(this T[,] matrix)
{
return matrix.GetLength(0);
}
/// <summary>
/// Gets the number of columns in a multidimensional matrix.
/// </summary>
///
/// <typeparam name="T">The type of the elements in the matrix.</typeparam>
/// <param name="matrix">The matrix whose number of columns must be computed.</param>
///
/// <returns>The number of columns in the matrix.</returns>
///
public static int Columns<T>(this T[,] matrix)
{
return matrix.GetLength(1);
}
/// <summary>
/// Returns true if a vector of real-valued observations
/// is ordered in ascending or descending order.
/// </summary>
///
/// <param name="values">An array of values.</param>
///
public static bool IsSorted<T>(this T[] values)
where T : IComparable<T>
{
return IsSorted(values, ComparerDirection.Ascending)
|| IsSorted(values, ComparerDirection.Descending);
}
/// <summary>
/// Returns true if a vector of real-valued observations
/// is ordered in ascending or descending order.
/// </summary>
///
/// <param name="values">An array of values.</param>
/// <param name="direction">The sort order direction.</param>
///
public static bool IsSorted<T>(this T[] values, ComparerDirection direction)
where T : IComparable<T>
{
if (direction == ComparerDirection.Ascending)
{
for (int i = 1; i < values.Length; i++)
if (values[i - 1].CompareTo(values[i]) > 0)
return false;
}
else
{
for (int i = 1; i < values.Length; i++)
if (values[i - 1].CompareTo(values[i]) < 0)
return false;
}
return true;
}
/// <summary>
/// Returns true if a matrix is square.
/// </summary>
///
public static bool IsSquare<T>(this T[][] matrix)
{
if (matrix == null)
throw new ArgumentNullException("matrix");
return matrix.Rows() == matrix.Columns(max: true);
}
/// <summary>
/// Returns true if a matrix is square.
/// </summary>
///
public static bool IsSquare<T>(this T[,] matrix)
{
if (matrix == null)
throw new ArgumentNullException("matrix");
return matrix.Rows() == matrix.Columns();
}
/// <summary>
/// Returns true if a matrix is upper triangular.
/// </summary>
public static bool IsUpperTriangular<T>(this T[,] matrix) where T : IComparable
{
if (matrix == null) throw new ArgumentNullException("matrix");
T zero = default(T);
if (matrix.GetLength(0) != matrix.GetLength(1))
return false;
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < i; j++)
if (matrix[i, j].CompareTo(zero) != 0)
return false;
return true;
}
/// <summary>
/// Returns true if a matrix is lower triangular.
/// </summary>
public static bool IsLowerTriangular<T>(this T[,] matrix) where T : IComparable
{
if (matrix == null) throw new ArgumentNullException("matrix");
T zero = default(T);
if (matrix.GetLength(0) != matrix.GetLength(1))
return false;
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = i + 1; j < matrix.GetLength(1); j++)
if (matrix[i, j].CompareTo(zero) != 0)
return false;
return true;
}
/// <summary>
/// Converts a matrix to lower triangular form, if possible.
/// </summary>
///
public static T[,] ToLowerTriangular<T>(this T[,] matrix, MatrixType from, T[,] result = null)
{
if (result == null)
result = Matrix.CreateAs(matrix);
matrix.CopyTo(result);
switch (from)
{
case MatrixType.LowerTriangular:
case MatrixType.Diagonal:
break;
case MatrixType.UpperTriangular:
Transpose(result, inPlace: true);
break;
default:
throw new ArgumentException("Only LowerTriangular, UpperTriangular and Diagonal matrices are supported at this time.", "matrixType");
}
return result;
}
/// <summary>
/// Converts a matrix to upper triangular form, if possible.
/// </summary>
///
public static T[,] ToUpperTriangular<T>(this T[,] matrix, MatrixType from, T[,] result = null)
{
if (result == null)
result = Matrix.CreateAs(matrix);
matrix.CopyTo(result);
switch (from)
{
case MatrixType.UpperTriangular:
case MatrixType.Diagonal:
break;
case MatrixType.LowerTriangular:
Transpose(result, inPlace: true);
break;
default:
throw new ArgumentException("Only LowerTriangular, UpperTriangular and Diagonal matrices are supported at this time.", "matrixType");
}
return result;
}
/// <summary>
/// Converts a matrix to lower triangular form, if possible.
/// </summary>
///
public static T[][] ToLowerTriangular<T>(this T[][] matrix, MatrixType from, T[][] result = null)
{
if (result == null)
result = Jagged.CreateAs(matrix);
matrix.CopyTo(result);
switch (from)
{
case MatrixType.LowerTriangular:
case MatrixType.Diagonal:
break;
case MatrixType.UpperTriangular:
Transpose(result, inPlace: true);
break;
default:
throw new ArgumentException("Only LowerTriangular, UpperTriangular and Diagonal matrices are supported at this time.", "matrixType");
}
return result;
}
/// <summary>
/// Converts a matrix to upper triangular form, if possible.
/// </summary>
///
public static T[][] ToUpperTriangular<T>(this T[][] matrix, MatrixType from, T[][] result = null)
{
if (result == null)
result = Jagged.CreateAs(matrix);
matrix.CopyTo(result);
switch (from)
{
case MatrixType.UpperTriangular:
case MatrixType.Diagonal:
break;
case MatrixType.LowerTriangular:
Transpose(result, inPlace: true);
break;
default:
throw new ArgumentException("Only LowerTriangular, UpperTriangular and Diagonal matrices are supported at this time.", "matrixType");
}
return result;
}
/// <summary>
/// Gets the lower triangular part of a matrix.
/// </summary>
///
public static T[,] GetLowerTriangle<T>(this T[,] matrix, bool includeDiagonal = true)
{
int s = includeDiagonal ? 1 : 0;
var r = Matrix.CreateAs(matrix);
for (int i = 0; i < matrix.Rows(); i++)
for (int j = 0; j < i + s; j++)
r[i, j] = matrix[i, j]; ;
return r;
}
/// <summary>
/// Gets the upper triangular part of a matrix.
/// </summary>
///
public static T[,] GetUpperTriangle<T>(this T[,] matrix, bool includeDiagonal = false)
{
int s = includeDiagonal ? 0 : 1;
var r = Matrix.CreateAs(matrix);
for (int i = 0; i < matrix.Rows(); i++)
for (int j = i + s; j < matrix.Columns(); j++)
r[i, j] = matrix[i, j]; ;
return r;
}
/// <summary>
/// Transforms a triangular matrix in a symmetric matrix by copying
/// its elements to the other, unfilled part of the matrix.
/// </summary>
///
public static T[,] GetSymmetric<T>(this T[,] matrix, MatrixType type, T[,] result = null)