/// <summary> /// Removes dimensions of length 1 from the array. /// </summary> /// <param name="array">The array.</param> public static Array Squeeze(this Array array) { var dimensions = array.GetLength().Where(x => x != 1).ToArray(); if (dimensions.Length == 0) { dimensions = new[] { 1 } } ; Array res; if (array.IsJagged()) { #if NETSTANDARD1_4 throw new NotSupportedException("Squeeze with jagged arrays is not supported in .NET Standard 1.4."); #else res = Jagged.Zeros(array.GetInnerMostType(), dimensions); Copy(array, res); #endif } else { res = Matrix.Zeros(array.GetInnerMostType(), dimensions); Buffer.BlockCopy(array, 0, res, 0, res.GetNumberOfBytes()); } return(res); }
/// <summary> /// Gets the transpose of a matrix. /// </summary> /// <param name="matrix">A matrix.</param> /// <returns>The transpose of the given matrix.</returns> public static TItem[][] Transpose <TCollection, TItem>(this TCollection matrix) where TCollection : ICollection, IEnumerable <TItem[]> { var rows = matrix.Count; if (rows == 0) { return(new TItem[rows][]); } var cols = matrix.Columns(); #if CHECKS if (!IsRectangular(matrix)) { throw new ArgumentException("Only rectangular matrices can be transposed."); } #endif var result = Jagged.Zeros <TItem>(cols, rows); var i = 0; foreach (var row in matrix) { for (var j = 0; j < result.Length; j++) { result[j][i] = row[j]; } i++; } return(result); }
/// <summary> /// Converts a matrix represented as a nested list of lists into a jagged matrix. /// </summary> public static T[][] ToJagged <T>(this IList <IList <T> > values) { var rows = values.Rows(); var cols = values.Columns(); var result = Jagged.Zeros <T>(rows, cols); for (var i = 0; i < values.Count; i++) { for (var j = 0; j < values[i].Count; j++) { result[i][j] = values[i][j]; } } return(result); }