// copying vector basis in several samples public static Matrix <float> VectorToMatrix(int columns, Vector <float> v) { List <Vector <float> > vv = new List <Vector <float> >(columns); // creating a list of column vectors for (int i = 0; i < columns; i++) { vv.Add(v); // initilizaing the matrix List } return(DenseMatrix.OfColumnVectors(vv)); // return the column list }
private static IContinuousDistribution continuousDistribution; // distribtuion // Generate Random Matrix public static Matrix <float> GenerateRandomMatrix(int rows, int columns, params int[] parameters) { if (parameters.Length < 1) { throw new Exception("Pass no parameters"); // check if at least 1 parameter has been passed } meanDistr = new float[] { 0 }; // meanValues is zero sigmaDistr = new float[] { (float)Math.Sqrt(1.0 / 1) }; // sum of sigmas CreateDistribution(parameters); // generate distirbiution return(DenseMatrix.CreateRandom(rows, columns, continuousDistribution)); // create a matrix with normal/unifrom distribution }
/// <summary> /// Converts a given bitmap into an input pattern of the network. /// </summary> /// <param name="inputBmp"></param> /// <returns>a Row*Col X 1 matrix containing the bitmap pixel</returns> public static Matrix<float> Bmp2Pattern(string path) { System.Drawing.Bitmap inputBmp = new Bitmap(path); Matrix<float> result = new DenseMatrix(inputBmp.Width * inputBmp.Height, 1); for(int row = 0; row < inputBmp.Height; row++) for (int col = 0; col < inputBmp.Width; col++) { result[(row * inputBmp.Width) + col, 0] = (Convert.ToSingle(inputBmp.GetPixel(row, col).R) + Convert.ToSingle(inputBmp.GetPixel(row, col).G) + Convert.ToSingle(inputBmp.GetPixel(row, col).B)) / (3.0f * 255.0f); } inputBmp.Dispose(); return result; }
public void CanCheckRankOfSquareSingular([Values(10, 50, 100)] int order) { var A = new DenseMatrix(order, order); A[0, 0] = 1; A[order - 1, order - 1] = 1; for (var i = 1; i < order - 1; i++) { A[i, i - 1] = 1; A[i, i + 1] = 1; A[i - 1, i] = 1; A[i + 1, i] = 1; } var factorEvd = A.Evd(); Assert.AreEqual(factorEvd.Determinant, 0); Assert.AreEqual(factorEvd.Rank, order - 1); }
public void CanCheckRankOfSquareSingular(int order) { var matrixA = new DenseMatrix(order, order); matrixA[0, 0] = 1; matrixA[order - 1, order - 1] = 1; for (var i = 1; i < order - 1; i++) { matrixA[i, i - 1] = 1; matrixA[i, i + 1] = 1; matrixA[i - 1, i] = 1; matrixA[i + 1, i] = 1; } var factorEvd = matrixA.Evd(); Assert.AreEqual(factorEvd.Determinant, 0); Assert.AreEqual(factorEvd.Rank, order - 1); }
public static Matrix <float> GenerateMatrix(Matrix <float> Sample) { int rows, columns; DimsOfMatrix(Sample.ToTypeString(), out rows, out columns); int[] maxIndex = new int[columns]; float[] maxValue = new float[columns]; Func <int, int, float> Filter = (int j, int i) => j == maxIndex[i] ? 1 : 0; for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { maxIndex[i] = maxValue[i] < Sample[j, i] ? j : maxIndex[i]; maxValue[i] = maxValue[i] < Sample[j, i] ? Sample[j, i] : maxValue[i]; } // work on it further // the plan is simle// classical trajectoreis, supervised learning } // here we need to figure out how to extract dimenstions from a matrix return(DenseMatrix.Create(rows, columns, Filter)); }
public void CanAddSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); var sum1 = m1 + m2; var sum2 = m2 + m1; Assert.IsTrue(sum1.Equals(m2)); Assert.IsTrue(sum1.Equals(sum2)); var sparseResult = new SparseMatrix(1, 3); sparseResult.Add(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Add(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); m1.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(2*sum1)); var denseResult = new DenseMatrix(1, 3); denseResult.Add(m2, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); denseResult = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); denseResult.Add(m1, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); var m3 = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); var sum3 = m1 + m3; var sum4 = m3 + m1; Assert.IsTrue(sum3.Equals(m3)); Assert.IsTrue(sum3.Equals(sum4)); }
Evd evd; //factorization storage #endregion Fields #region Constructors public vanillaLogCov(float[,] matrix1, float[,] matrix2) { //deep copy the covariances //densematrix allocates new memory for the matrix cov1 = new DenseMatrix(Covariance(matrix1)); cov2 = new DenseMatrix(Covariance(matrix2)); evd = cov1.Evd(); diag = evd.D(); //could make this a function but thats for later cleanup.... < . < //should be square matrix so matrix lengths dont matter for (int i = 0; i < diag.RowCount; i++) { diag[i, i] = (float)Math.Log(Math.Abs((double)diag[i, i])); } logcov1 = evd.EigenVectors() * diag * evd.EigenVectors().Transpose(); evd = cov2.Evd(); diag = evd.D(); //could make this a function but thats for later cleanup.... < . < //should be square matrix so matrix lengths dont matter for (int i = 0; i < diag.RowCount; i++) { diag[i, i] = (float)Math.Log(Math.Abs((double)diag[i, i])); } logcov2 = evd.EigenVectors() * diag * evd.EigenVectors().Transpose(); //compute distance distance = 0; //initialize to empty for (int i = 0; i < logcov2.RowCount; i++) { for (int j = 0; j < logcov2.RowCount; j++) { distance += (float)Math.Pow(logcov1[i, j] - logcov2[i, j], 2); } } distance = (float)Math.Sqrt(distance); }
/// <summary> /// Returns the transpose of this matrix. /// </summary> /// <returns>The transpose of this matrix.</returns> public override Matrix<float> Transpose() { var ret = new DenseMatrix(ColumnCount, RowCount); for (var j = 0; j < ColumnCount; j++) { var index = j * RowCount; for (var i = 0; i < RowCount; i++) { ret.Data[(i * ColumnCount) + j] = Data[index + i]; } } return ret; }
public void CanComputeQRFactorWideMatrix() { var matrix = _matrices["Wide2x3"]; var r = new float[matrix.RowCount*matrix.ColumnCount]; Array.Copy(matrix.Values, r, r.Length); var tau = new float[3]; var q = new float[matrix.RowCount*matrix.RowCount]; Control.LinearAlgebraProvider.QRFactor(r, matrix.RowCount, matrix.ColumnCount, q, tau); var mr = new DenseMatrix(matrix.RowCount, matrix.ColumnCount, r).UpperTriangle(); var mq = new DenseMatrix(matrix.RowCount, matrix.RowCount, q); var a = mq*mr; for (var row = 0; row < matrix.RowCount; row++) { for (var col = 0; col < matrix.ColumnCount; col++) { AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 5); } } }
/// <summary> /// Fill this info in /// </summary> /// <param name="vDirection"> /// </param> /// <returns> /// Fill this info in /// </returns> public static IQuaternion GenerateRotationFromDirectionVector(IVector3 vDirection) { // Step 1. Setup basis vectors describing the rotation given the input vector and assuming an initial up direction of (0, 1, 0) Vector3 vDirNormalized = Vector3.Normalize((Vector3)vDirection); Vector3 vUp = new Vector3(0, 1.0f, 0.0f); // Y Up vector Vector3 vRight = Vector3.Cross(vUp, vDirNormalized); // The perpendicular vector to Up and Direction vUp = Vector3.Cross(vDirNormalized, vRight); // The actual up vector given the direction and the right vector // Step 2. Put the three vectors into the matrix to bulid a basis rotation matrix // This step isnt necessary, but im adding it because often you would want to convert from matricies to quaternions instead of vectors to quaternions // If you want to skip this step, you can use the vector values directly in the quaternion setup below Matrix mBasis = new DenseMatrix(4, 4); mBasis.SetRow(0, new[] { (float)vRight.x, (float)vRight.y, (float)vRight.z, 0.0f }); mBasis.SetRow(1, new[] { (float)vUp.x, (float)vUp.y, (float)vUp.z, 0.0f }); mBasis.SetRow(2, new[] { (float)vDirNormalized.x, (float)vDirNormalized.y, (float)vDirNormalized.z, 0.0f }); mBasis.SetRow(3, new[] { 0.0f, 0.0f, 0.0f, 1.0f }); // Step 3. Build a quaternion from the matrix double dfWScale = Math.Sqrt(1.0f + mBasis.At(0, 0) + mBasis.At(1, 1) + mBasis.At(2, 2)) / 2.0f * 4.0; if (dfWScale == 0.0) { Quaternion q = new Quaternion(0, 1, 0, 0); return q; } Quaternion qrot = new Quaternion( (float)((mBasis.At(3, 2) - mBasis.At(2, 3)) / dfWScale), (float)((mBasis.At(0, 2) - mBasis.At(2, 0)) / dfWScale), (float)((mBasis.At(1, 0) - mBasis.At(0, 1)) / dfWScale), (float)Math.Sqrt(1.0f + mBasis.At(0, 0) + mBasis.At(1, 1) + mBasis.At(2, 2)) / 2.0f); var temp = qrot.w; qrot.w = qrot.y; qrot.y = temp; return qrot.Normalize(); }
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order) { var matrixA = Matrix<float>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorGramSchmidt = matrixA.GramSchmidt(); var matrixB = Matrix<float>.Build.Random(order, order, 1); var matrixBCopy = matrixB.Clone(); var matrixX = new DenseMatrix(order, order); factorGramSchmidt.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-3); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } }
// Matrix Multiplications public static Matrix <float> GenerateMatrix(int rows, int colums) { return(DenseMatrix.Create(rows, colums, 0)); }
/// <summary> /// Adds another matrix to this matrix. /// </summary> /// <param name="other">The matrix to add to this matrix.</param> /// <returns>The result of the addition.</returns> /// <exception cref="ArgumentNullException">If the other matrix is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException">If the two matrices don't have the same dimensions.</exception> public override Matrix<float> Add(Matrix<float> other) { if (other == null) { throw new ArgumentNullException("other"); } if (other.RowCount != RowCount || other.ColumnCount != ColumnCount) { throw new ArgumentOutOfRangeException("other", Resources.ArgumentMatrixDimensions); } Matrix<float> result; if (other is DiagonalMatrix) { result = new DiagonalMatrix(RowCount, ColumnCount); } else { result = new DenseMatrix(RowCount, ColumnCount); } Add(other, result); return result; }
/// <summary> /// Create a new dense matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static DenseMatrix OfDiagonalArray(int rows, int columns, float[] diagonal) { var m = new DenseMatrix(rows, columns); m.SetDiagonal(diagonal); return m; }
/// <summary> /// Create a new dense matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static DenseMatrix OfDiagonalVector(int rows, int columns, Vector<float> diagonal) { var m = new DenseMatrix(rows, columns); m.SetDiagonal(diagonal); return m; }
/// <summary> /// Create a matrix based on this vector in row form (one single row). /// </summary> /// <returns>This vector as a row matrix.</returns> public override Matrix<float> ToRowMatrix() { var matrix = new DenseMatrix(1, _length); for (var i = 0; i < _values.Length; i++) { matrix.At(0, i, _values[i]); } return matrix; }
/// <summary> /// Subtracts another matrix from this matrix. /// </summary> /// <param name="other">The matrix to subtract.</param> /// <returns>The result of the subtraction.</returns> /// <exception cref="ArgumentNullException">If the other matrix is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException">If the two matrices don't have the same dimensions.</exception> public override Matrix<float> Subtract(Matrix<float> other) { if (other == null) { throw new ArgumentNullException("other"); } if (other.RowCount != RowCount || other.ColumnCount != ColumnCount) { throw DimensionsDontMatch<ArgumentOutOfRangeException>(this, other, "other"); } Matrix<float> result; if (other is DiagonalMatrix) { result = new DiagonalMatrix(RowCount, ColumnCount); } else { result = new DenseMatrix(RowCount, ColumnCount); } Subtract(other, result); return result; }
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int column) { var matrixA = MatrixLoader.GenerateRandomDenseMatrix(row, column); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(true); var matrixB = MatrixLoader.GenerateRandomDenseMatrix(row, column); var matrixBCopy = matrixB.Clone(); var matrixX = new DenseMatrix(column, column); factorSvd.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } }
/// <summary> /// Initializes a square <see cref="DenseMatrix"/> with all zero's except for ones on the diagonal. /// </summary> /// <param name="order">the size of the square matrix.</param> /// <returns>A dense identity matrix.</returns> /// <exception cref="ArgumentException"> /// If <paramref name="order"/> is less than one. /// </exception> public static DenseMatrix Identity(int order) { var m = new DenseMatrix(order); for (var i = 0; i < order; i++) { m._data[(i * order) + i] = 1.0f; } return m; }
public void CanSolveUsingThinQRTallMatrixUsingWorkArray() { var matrix = _matrices["Tall3x2"]; var a = new float[matrix.RowCount*matrix.ColumnCount]; Array.Copy(matrix.Values, a, a.Length); var b = new[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; var x = new float[matrix.ColumnCount*2]; var work = new float[matrix.RowCount*matrix.ColumnCount]; Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x, work, QRMethod.Thin); NotModified(3, 2, a, matrix); var mb = new DenseMatrix(matrix.RowCount, 2, b); var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb; AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 5); AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 5); AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 5); AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 5); }
public void CanSolveUsingThinQRSquareMatrixUsingWorkArray() { var matrix = _matrices["Square3x3"]; var a = new float[matrix.RowCount*matrix.ColumnCount]; Array.Copy(matrix.Values, a, a.Length); var b = new[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; var x = new float[matrix.ColumnCount*2]; var work = new float[matrix.RowCount*matrix.ColumnCount]; Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x, work, QRMethod.Thin); NotModified(3, 3, a, matrix); var mx = new DenseMatrix(matrix.ColumnCount, 2, x); var mb = matrix*mx; AssertHelpers.AlmostEqualRelative(mb[0, 0], b[0], 5); AssertHelpers.AlmostEqualRelative(mb[1, 0], b[1], 5); AssertHelpers.AlmostEqualRelative(mb[2, 0], b[2], 5); AssertHelpers.AlmostEqualRelative(mb[0, 1], b[3], 5); AssertHelpers.AlmostEqualRelative(mb[1, 1], b[4], 4); AssertHelpers.AlmostEqualRelative(mb[2, 1], b[5], 4); }
public void CanSolveUsingSVDTallMatrixOnFactoredMatrix() { var matrix = _matrices["Tall3x2"]; var a = new float[matrix.RowCount*matrix.ColumnCount]; Array.Copy(matrix.Values, a, a.Length); var s = new float[matrix.ColumnCount]; var u = new float[matrix.RowCount*matrix.RowCount]; var vt = new float[matrix.ColumnCount*matrix.ColumnCount]; Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt); var b = new[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; var x = new float[matrix.ColumnCount*2]; Control.LinearAlgebraProvider.SvdSolveFactored(matrix.RowCount, matrix.ColumnCount, s, u, vt, b, 2, x); var mb = new DenseMatrix(matrix.RowCount, 2, b); var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb; AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 5); AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 5); AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 5); AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 5); }
/// <summary> /// Returns the transpose of this matrix. /// </summary> /// <returns>The transpose of this matrix.</returns> public override Matrix<float> Transpose() { var ret = new DenseMatrix(_columnCount, _rowCount); for (var j = 0; j < _columnCount; j++) { var index = j * _rowCount; for (var i = 0; i < _rowCount; i++) { ret._data[(i * _columnCount) + j] = _data[index + i]; } } return ret; }
public void CanComputeSVDFactorizationOfWideMatrixWithWorkArray() { var matrix = _matrices["Wide2x3"]; var a = new float[matrix.RowCount*matrix.ColumnCount]; Array.Copy(matrix.Values, a, a.Length); var s = new float[matrix.RowCount]; var u = new float[matrix.RowCount*matrix.RowCount]; var vt = new float[matrix.ColumnCount*matrix.ColumnCount]; var work = new float[100]; Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt, work); var w = new DenseMatrix(matrix.RowCount, matrix.ColumnCount); for (var index = 0; index < s.Length; index++) { w[index, index] = s[index]; } var mU = new DenseMatrix(matrix.RowCount, matrix.RowCount, u); var mV = new DenseMatrix(matrix.ColumnCount, matrix.ColumnCount, vt); var result = mU*w*mV; AssertHelpers.AlmostEqualRelative(matrix[0, 0], result[0, 0], 5); AssertHelpers.AlmostEqualRelative(matrix[1, 0], result[1, 0], 5); AssertHelpers.AlmostEqualRelative(matrix[0, 1], result[0, 1], 5); AssertHelpers.AlmostEqualRelative(matrix[1, 1], result[1, 1], 5); AssertHelpers.AlmostEqualRelative(matrix[0, 2], result[0, 2], 5); AssertHelpers.AlmostEqualRelative(matrix[1, 2], result[1, 2], 5); }
/// <summary> /// Create a matrix based on this vector in column form (one single column). /// </summary> /// <returns>This vector as a column matrix.</returns> public override Matrix<float> ToColumnMatrix() { var matrix = new DenseMatrix(_length, 1); for (var i = 0; i < _values.Length; i++) { matrix.At(i, 0, _values[i]); } return matrix; }
public void CanComputeThinQRFactorTallMatrixWithWorkArray() { var matrix = _matrices["Tall3x2"]; var r = new float[matrix.ColumnCount*matrix.ColumnCount]; var tau = new float[3]; var q = new float[matrix.RowCount*matrix.ColumnCount]; Array.Copy(matrix.Values, q, q.Length); var work = new float[matrix.ColumnCount*Control.BlockSize]; Control.LinearAlgebraProvider.ThinQRFactor(q, matrix.RowCount, matrix.ColumnCount, r, tau, work); var mq = new DenseMatrix(matrix.RowCount, matrix.ColumnCount, q); var mr = new DenseMatrix(matrix.ColumnCount, matrix.ColumnCount, r); var a = mq*mr; for (var row = 0; row < matrix.RowCount; row++) { for (var col = 0; col < matrix.ColumnCount; col++) { AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 5); } } }
/// <summary> /// Outer product of two vectors /// </summary> /// <param name="u">First vector</param> /// <param name="v">Second vector</param> /// <returns>Matrix M[i,j] = u[i]*v[j] </returns> /// <exception cref="ArgumentNullException">If the u vector is <see langword="null" />.</exception> /// <exception cref="ArgumentNullException">If the v vector is <see langword="null" />.</exception> public static DenseMatrix OuterProduct(DenseVector u, DenseVector v) { if (u == null) { throw new ArgumentNullException("u"); } if (v == null) { throw new ArgumentNullException("v"); } var matrix = new DenseMatrix(u.Count, v.Count); CommonParallel.For( 0, u.Count, i => { for (var j = 0; j < v.Count; j++) { matrix.At(i, j, u._values[i] * v._values[j]); } }); return matrix; }
public void CanMultiplyTallAndWideMatrices() { var x = _matrices["Tall3x2"]; var y = _matrices["Wide2x3"]; var c = new DenseMatrix(x.RowCount, y.ColumnCount); Control.LinearAlgebraProvider.MatrixMultiply(x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, c.Values); for (var i = 0; i < c.RowCount; i++) { for (var j = 0; j < c.ColumnCount; j++) { AssertHelpers.AlmostEqualRelative(x.Row(i)*y.Column(j), c[i, j], 5); } } }
/// <summary> /// Create a new dense matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static DenseMatrix OfDiagonalArray(float[] diagonal) { var m = new DenseMatrix(diagonal.Length, diagonal.Length); m.SetDiagonal(diagonal); return m; }
public void CanMultiplyTallAndWideMatricesWithUpdate() { var x = _matrices["Tall3x2"]; var y = _matrices["Wide2x3"]; var c = new DenseMatrix(x.RowCount, y.ColumnCount); Control.LinearAlgebraProvider.MatrixMultiplyWithUpdate(Transpose.DontTranspose, Transpose.DontTranspose, 2.2f, x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, 1.0f, c.Values); for (var i = 0; i < c.RowCount; i++) { for (var j = 0; j < c.ColumnCount; j++) { var test = 2.2f*x.Row(i)*y.Column(j); // if they are both close to zero, skip if (Math.Abs(test) < 1e-7 && Math.Abs(c[i, j]) < 1e-7) { continue; } AssertHelpers.AlmostEqualRelative(2.2f*x.Row(i)*y.Column(j), c[i, j], 5); } } }
/// <summary> /// Create a new dense matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static DenseMatrix OfDiagonalVector(Vector<float> diagonal) { var m = new DenseMatrix(diagonal.Count, diagonal.Count); m.SetDiagonal(diagonal); return m; }
public void CanMultiplyWideAndTallMatricesWithUpdate() { var x = _matrices["Wide2x3"]; var y = _matrices["Tall3x2"]; var c = new DenseMatrix(x.RowCount, y.ColumnCount); Control.LinearAlgebraProvider.MatrixMultiplyWithUpdate(Transpose.DontTranspose, Transpose.DontTranspose, 2.2f, x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, 1.0f, c.Values); for (var i = 0; i < c.RowCount; i++) { for (var j = 0; j < c.ColumnCount; j++) { AssertHelpers.AlmostEqualRelative(2.2f*x.Row(i)*y.Column(j), c[i, j], 5); } } }
void fuseRange(BuildData data, int first, int last) { int colCount = last - first; var sum = Vector3.Zero; for (int i = 0; i < colCount; i++) { sum += data.points[data.indices[first + i]].point; } var mean = sum / colCount; var NN = new MathNet.Numerics.LinearAlgebra.Single.DenseMatrix(3, colCount); var min = new Vector3(float.MaxValue); var max = new Vector3(float.MinValue); for (int i = 0; i < colCount; i++) { var v = data.points[data.indices[first + i]].point; var p = v - mean; NN.At(0, i, p.X); NN.At(1, i, p.Y); NN.At(2, i, p.Z); min = Vector3.Min(min, v); max = Vector3.Max(max, v); } Vector3 box = max - min; float boxDim = GetAt(box, MaxDim(box)); // drop box if it is too large if (boxDim > maxBoxDim) { data.unfitPointsCount += colCount; return; } // compute covariance var C = NN.TransposeAndMultiply(NN); var eigen = C.Evd(); // Ensure that the matrix is suited for eigenvalues calculation if (eigen.Rank < 2) { data.unfitPointsCount += colCount; return; } var normal = computeNormal(eigen.EigenValues(), eigen.EigenVectors()); /*T densitie = 0; * if(keepDensities) * densitie = SurfaceNormalDataPointsFilter::computeDensity(NN);*/ // Filter points randomly if (samplingMethod == SamplingMethod.RandomSampling) { for (int i = 0; i < colCount; i++) { float x = (float)r.NextDouble(); if (x < ratio) { // Keep points with their descriptors int k = data.indices[first + i]; // Mark the indices which will be part of the final data data.pointsToKeep.Add(new DataPoint { point = data.points[k].point, normal = normal, });; } } } else if (samplingMethod == SamplingMethod.Bin) { // Use the average and norm data.pointsToKeep.Add(new DataPoint { point = mean, normal = normal }); } }
private void processMatrix(ChannelData channel, float[] buffer, int count) { var c = coefficients.Length; var src = 1 - c; var dst = 0; var offset = c - 1; matrix = BufferHelpers.Ensure(matrix, count * c); history = BufferHelpers.Ensure(history, c); channel.InputHistory = BufferHelpers.Ensure(channel.InputHistory, c); Buffer.BlockCopy(channel.InputHistory, 0, history, 0, sizeof(float) * c); for (int i = 0; i < count; i++) { Buffer.BlockCopy( buffer, sizeof(float) * (src + offset), matrix, sizeof(float) * (dst + offset), sizeof(float) * (c - offset)); if (offset > 0) { Buffer.BlockCopy( history, sizeof(float) * (c - offset), matrix, sizeof(float) * dst, sizeof(float) * offset); offset -= 1; } src += 1; dst += c; } Buffer.BlockCopy(buffer, sizeof(float) * (count - c), channel.InputHistory, 0, sizeof(float) * c); var X = new DenseMatrix(coefficients.Length, count, matrix); var B = new DenseMatrix(1, count, buffer); C.Multiply(X, B); }