Module_LinearAlgebra - vorcyc/Vorcyc.Mathematics GitHub Wiki

Location: Home / Linear algebra

Linear algebra module

The Vorcyc.Mathematics.LinearAlgebra namespace includes linear algebra types such as BasisTransformation, LinearEquationSolver, MatrixFp32, Matrix<T>, MatrixDecomposition, MatrixDiagnostics, MatrixHelper, MatrixOperations, Quaternion<T>, TensorFp32, Tensor<T>, Tensor4D<T>, TensorOps, and VectorSpan. Math vectors are represented as ReadOnlySpan<T> / Span<T> / T[]; VectorSpan provides dot products, norms, and related operations while avoiding naming clashes with BCL System.Numerics.Vector<T> (SIMD). 4D data is stored in layout-neutral Tensor4D<T>; the deep learning module's BatchTensor<T> (NHWC) wraps batch semantics on top.

All types below are in the namespace Vorcyc.Mathematics.LinearAlgebra

📒 Contents


Vorcyc.Mathematics.LinearAlgebra.BasisTransformation class

BasisTransformation is a static class for basis transformations.

Methods

1. Transform

  • public static T[] Transform<T>(T[] vector, Matrix<T> fromBasis, Matrix<T> toBasis) where T : struct, IFloatingPointIeee754<T>
    • Transforms a vector from one basis to another.
    • Parameters:
      • vector: Vector to transform.
      • fromBasis: Source basis.
      • toBasis: Target basis.
    • Returns: Transformed vector.
    • Exceptions:
      • ArgumentException: Thrown when basis dimensions do not match。

Code example

The following example uses BasisTransformation Transform with comments:

using System; 
using Vorcyc.Mathematics.LinearAlgebra;

public class BasisTransformationExample 
{ 
    public static void Main() 
    { 
        // Vector and basis matrices 
        double[] vector = { 1.0, 2.0, 3.0 };
        Matrix<double> fromBasis = new Matrix<double>(new double[,] { { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 } });
        Matrix<double> toBasis = new Matrix<double>(new double[,] { { 0.0, 1.0, 0.0 }, { 1.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0 } });
    
        // Transform basis
        double[] transformedVector = BasisTransformation.Transform(vector, fromBasis, toBasis);

        // Print transformed vector
        Console.WriteLine("Transformed Vector: " + string.Join(", ", transformedVector));
    }
}

Vorcyc.Mathematics.LinearAlgebra.LinearEquationSolver class

LinearEquationSolver is a static class for solving linear systems.

Methods

1. GaussianEliminationSolve

  • public static T[] GaussianEliminationSolve<T>(Matrix<T> A, T[] b) where T : struct, IFloatingPointIeee754<T>

    • Solves Ax = b with Gaussian elimination.
    • Parameters:
      • A: Coefficient matrix.
      • b: Right-hand side vector.
    • Returns: Solution vector x.
    • Exceptions:
      • ArgumentException: Thrown when A is not square or dimensions of A and b do not match。
  • public static void GaussianEliminationSolve<T>(Matrix<T> A, ReadOnlySpan<T> b, Span<T> x, T[,]? augmentedWorkspace = null) where T : struct, IFloatingPointIeee754<T>

    • Solves Ax = b in place into x; optional augmentedWorkspace (n×(n+1)) avoids reallocating the augmented matrix.

2. LUSolve

  • public static T[] LUSolve<T>(Matrix<T> A, T[] b) where T : struct, IFloatingPointIeee754<T>
    • Solves Ax = b with LU decomposition.
    • Parameters:
      • A: Coefficient matrix.
      • b: Right-hand side vector.
    • Returns: Solution vector x.
    • Exceptions:
      • ArgumentException: Thrown when A is not square or dimensions of A and b do not match。

3. JacobiSolve

  • public static T[] JacobiSolve<T>(Matrix<T> A, T[] b, T tolerance, int maxIterations = 1000) where T : struct, IFloatingPointIeee754<T>
    • Solves Ax = b with the Jacobi method.
    • Parameters:
      • A: Coefficient matrix.
      • b: Right-hand side vector.
      • tolerance: Convergence tolerance.
      • maxIterations: Maximum iterations.
    • Returns: Solution vector x.
    • Exceptions:
      • ArgumentException: Thrown when A is not square or dimensions of A and b do not match。

4. GaussSeidelSolve

  • public static T[] GaussSeidelSolve<T>(Matrix<T> A, T[] b, T tolerance, int maxIterations = 1000) where T : struct, IFloatingPointIeee754<T>
    • Solves Ax = b with Gauss–Seidel.
    • Parameters:
      • A: Coefficient matrix.
      • b: Right-hand side vector.
      • tolerance: Convergence tolerance.
      • maxIterations: Maximum iterations.
    • Returns: Solution vector x.
    • Exceptions:
      • ArgumentException: Thrown when A is not square or dimensions of A and b do not match。

5. CholeskySolve

  • public static T[] CholeskySolve<T>(Matrix<T> A, T[] b) — symmetric positive definite Ax = b (A = LLᵀ)

6. SolveLeastSquares / SolveRidgeLeastSquares

  • SolveLeastSquares<T>(Matrix<T> designMatrix, ReadOnlySpan<T> y) — min ‖Ax − y‖²; normal equations first, SVD when ill-conditioned
  • SolveRidgeLeastSquares<T>(Matrix<T> designMatrix, ReadOnlySpan<T> y, T lambda, bool regularizeIntercept = true) — ridge regression

7. SolveLeastSquaresSvd

  • SolveLeastSquaresSvd<T>(Matrix<T> designMatrix, ReadOnlySpan<T> y, T? tolerance = null) — thin SVD pseudoinverse for rank-deficient design matrices

Code example

The following example uses LinearEquationSolver with comments:

using System; using Vorcyc.Mathematics.LinearAlgebra;

public class LinearEquationSolverExample 
{
    public static void Main() 
    { 
        Matrix<double> A = new Matrix<double>(new double[,] { { 2.0, -1.0, 0.0 }, { -1.0, 2.0, -1.0 }, { 0.0, -1.0, 2.0 } });
        double[] b = { 1.0, 0.0, 1.0 };

        // Gaussian elimination
        double[] x1 = LinearEquationSolver.GaussianEliminationSolve(A, b);
        Console.WriteLine("Gaussian Elimination Solution: " + string.Join(", ", x1));

        // LU decomposition
        double[] x2 = LinearEquationSolver.LUSolve(A, b);
        Console.WriteLine("LU Decomposition Solution: " + string.Join(", ", x2));

        // Jacobi method
        double[] x3 = LinearEquationSolver.JacobiSolve(A, b, 1e-10);
        Console.WriteLine("Jacobi Method Solution: " + string.Join(", ", x3));

        // Gauss–Seidel method
        double[] x4 = LinearEquationSolver.GaussSeidelSolve(A, b, 1e-10);
        Console.WriteLine("Gauss-Seidel Method Solution: " + string.Join(", ", x4));
    }

}

Vorcyc.Mathematics.LinearAlgebra.MatrixFp32 class

MatrixFp32 represents a 2D matrix with basic operations.

Properties

1. Rows

  • public int Rows { get; }
    • Gets row count.

2. Columns

  • public int Columns { get; }
    • Gets column count.

Constructors

1. MatrixFp32(int rows, int columns)

  • public MatrixFp32(int rows, int columns)
    • Constructs matrix with given rows and columns.
    • Parameters:
      • rows: Row count.
      • columns: Column count.

2. MatrixFp32(int size)

  • public MatrixFp32(int size)
    • Constructs square matrix of given size.
    • Parameters:
      • size: MatrixFp32 size (rows and columns).

3. MatrixFp32(float[,] initialValues)

  • public MatrixFp32(float[,] initialValues)
    • Constructs matrix from 2D array.
    • Parameters:
      • initialValues: Initial values as 2D array.

Indexers

1. this[int row, int column]

  • public ref float this[int row, int column]
    • Gets or sets element at position.
    • Parameters:
      • row: Row index.
      • column: Column index.
    • Returns: Element at position.

Implicit conversions

1. Implicit conversion to 2D array

  • public static implicit operator float[,](MatrixFp32 matrix)
    • Implicitly converts matrix to 2D array.
    • Parameters:
      • matrix: MatrixFp32 to convert.

2. Implicit conversion to jagged array

  • public static implicit operator float[][](MatrixFp32 matrix)
    • Implicitly converts matrix to jagged array.
    • Parameters:
      • matrix: MatrixFp32 to convert.

3. Implicit conversion to matrix

  • public static implicit operator MatrixFp32(float[][] values)

    • Implicitly converts jagged array to matrix.
    • Parameters:
      • values: Jagged array to convert.
  • public static implicit operator MatrixFp32(float[,] values)

    • Implicitly converts 2D array to matrix.
    • Parameters:
      • values: 2D array to convert.

Operators

1. MatrixFp32 addition

  • public static MatrixFp32 operator +(MatrixFp32 a, MatrixFp32 b)
    • MatrixFp32 addition operator.
    • Parameters:
      • a: First matrix.
      • b: Second matrix.
    • Returns: Sum of two matrices.

2. MatrixFp32 subtraction

  • public static MatrixFp32 operator -(MatrixFp32 a, MatrixFp32 b)
    • MatrixFp32 subtraction operator.
    • Parameters:
      • a: First matrix.
      • b: Second matrix.
    • Returns: Difference of two matrices.

3. MatrixFp32 multiplication

  • public static MatrixFp32 operator *(MatrixFp32 a, MatrixFp32 b)
    • MatrixFp32 multiplication operator.
    • Parameters:
      • a: First matrix.
      • b: Second matrix.
    • Returns: Product of two matrices.

4. MatrixFp32–scalar multiplication

  • public static MatrixFp32 operator *(MatrixFp32 matrix, float scalar)
    • MatrixFp32–scalar multiplication operator.
    • Parameters:
      • matrix: MatrixFp32.
      • scalar: Scalar.
    • Returns: MatrixFp32 times scalar.

5. MatrixFp32–scalar division

  • public static MatrixFp32 operator /(MatrixFp32 matrix, float scalar)
    • MatrixFp32–scalar division operator.
    • Parameters:
      • matrix: MatrixFp32.
      • scalar: Scalar.
    • Returns: MatrixFp32 divided by scalar.

Methods

1. GetRow

  • public Span<float> GetRow(int rowIndex)
    • Gets elements of the specified row.
    • Parameters:
      • rowIndex: Row index.
    • Returns: Span of row elements.

2. GetColumn

  • public ReadOnlySpan<float> GetColumn(int columnIndex)
    • Gets elements of the specified column.
    • Parameters:
      • columnIndex: Column index.
    • Returns: ReadOnlySpan of column elements.

3. Transpose

  • public MatrixFp32 Transpose()
    • Transposes the matrix.
    • Returns: Transposed matrix.

4. Determinant

  • public float Determinant()
    • Computes the matrix determinant.
    • Returns: Determinant.

5. Inverse

  • public MatrixFp32 Inverse()
    • Computes the matrix inverse.
    • Returns: Inverse matrix.

6. LUDecomposition

  • public void LUDecomposition(out MatrixFp32 L, out MatrixFp32 U, out int[] P)
    • LU decomposition with partial pivoting.
    • Parameters:
      • L: Output lower triangular matrix.
      • U: Output upper triangular matrix.
      • P: Output pivot permutation array.

7. QRDecomposition

  • public void QRDecomposition(out MatrixFp32 Q, out MatrixFp32 R)
    • QR decomposition.
    • Parameters:
      • Q: Output orthogonal matrix.
      • R: Output upper triangular matrix.

8. CholeskyDecomposition

  • public MatrixFp32 CholeskyDecomposition()
    • Cholesky decomposition.
    • Returns: Lower triangular matrix.

9. Eye

  • public static MatrixFp32 Eye(int size)
    • Creates an identity matrix.
    • Parameters:
      • size: MatrixFp32 size (rows and columns).
    • Returns: Identity matrix.

10. Companion

  • public static MatrixFp32 Companion(float[] a)
    • Creates a companion matrix.
    • Parameters:
      • a: Polynomial coefficients.
    • Returns: Companion matrix.
    • Exceptions:
      • ArgumentException: Thrown when coefficient array length < 2 or first coefficient is zero。

11. FillRandom

  • public void FillRandom()
    • Fills matrix with random values.

12. Clone

  • public MatrixFp32 Clone()
    • Creates a deep copy.
    • Returns: Deep copy.

13. ToString

  • public override string ToString()
    • Returns string representation of matrix.
    • Returns: String representation.

Code example

The following example uses MatrixFp32 with comments:

using System; 
using Vorcyc.Mathematics.LinearAlgebra;

public class MatrixExample 
{ 
    public static void Main() 
    { 
        // Construct matrix from 2D array 
        MatrixFp32 matrixA = new MatrixFp32(new float[,] { { 1.0f, 2.0f, 3.0f }, { 4.0f, 5.0f, 6.0f }, { 7.0f, 8.0f, 9.0f } });

        // Construct matrix by size
        MatrixFp32 matrixB = new MatrixFp32(3, 3);
        matrixB.FillRandom();

        // MatrixFp32 addition
        MatrixFp32 sum = matrixA + matrixB;
        Console.WriteLine("Sum of matrices:\n" + sum);

        // MatrixFp32 subtraction
        MatrixFp32 difference = matrixA - matrixB;
        Console.WriteLine("Difference of matrices:\n" + difference);

        // MatrixFp32 multiplication
        MatrixFp32 product = matrixA * matrixB;
        Console.WriteLine("Product of matrices:\n" + product);

        // Transpose
        MatrixFp32 transpose = matrixA.Transpose();
        Console.WriteLine("Transpose of matrixA:\n" + transpose);

        // Determinant
        float determinant = matrixA.Determinant();
        Console.WriteLine("Determinant of matrixA: " + determinant);

        // Inverse
        MatrixFp32 inverse = matrixA.Inverse();
        Console.WriteLine("Inverse of matrixA:\n" + inverse);

        // LU decomposition
        matrixA.LUDecomposition(out MatrixFp32 L, out MatrixFp32 U, out int[] P);
        Console.WriteLine("L matrix from LU decomposition:\n" + L);
        Console.WriteLine("U matrix from LU decomposition:\n" + U);

        // QR decomposition
        matrixA.QRDecomposition(out MatrixFp32 Q, out MatrixFp32 R);
        Console.WriteLine("Q matrix from QR decomposition:\n" + Q);
        Console.WriteLine("R matrix from QR decomposition:\n" + R);

        // Cholesky decomposition
        MatrixFp32 cholesky = matrixA.CholeskyDecomposition();
        Console.WriteLine("Cholesky decomposition of matrixA:\n" + cholesky);

        // Identity matrix
        MatrixFp32 identity = MatrixFp32.Eye(3);
        Console.WriteLine("Identity matrix:\n" + identity);

        // Companion matrix
        MatrixFp32 companion = MatrixFp32.Companion(new float[] { 1.0f, -6.0f, 11.0f, -6.0f });
        Console.WriteLine("Companion matrix:\n" + companion);

        // Deep copy
        MatrixFp32 clone = matrixA.Clone();
        Console.WriteLine("Clone of matrixA:\n" + clone);
    }
}

Vorcyc.Mathematics.LinearAlgebra.MatrixFp32<T> class

Matrix<T> is a generic 2D matrix with basic operations.

Properties

1. Rows

  • public int Rows { get; }
    • Gets row count.

2. Columns

  • public int Columns { get; }
    • Gets column count.

Constructors

1. MatrixFp32(int rows, int columns)

  • public MatrixFp32(int rows, int columns)
    • Constructs matrix with given rows and columns.
    • Parameters:
      • rows: Row count.
      • columns: Column count.

2. MatrixFp32(int size)

  • public MatrixFp32(int size)
    • Constructs square matrix of given size.
    • Parameters:
      • size: MatrixFp32 size (rows and columns).

3. MatrixFp32(T[,] initialValues)

  • public MatrixFp32(T[,] initialValues)
    • Constructs matrix from 2D array.
    • Parameters:
      • initialValues: Initial values as 2D array.

Indexers

1. this[int row, int column]

  • public ref T this[int row, int column]
    • Gets or sets element at position.
    • Parameters:
      • row: Row index.
      • column: Column index.
    • Returns: Element at position.

Implicit conversions

1. Implicit conversion to 2D array

  • public static implicit operator T[,](Matrix<T> matrix)
    • Implicitly converts matrix to 2D array.
    • Parameters:
      • matrix: MatrixFp32 to convert.

2. Implicit conversion to jagged array

  • public static implicit operator T[][](Matrix<T> matrix)
    • Implicitly converts matrix to jagged array.
    • Parameters:
      • matrix: MatrixFp32 to convert.

3. Implicit conversion to matrix

  • public static implicit operator Matrix<T>(T[][] values)

    • Implicitly converts jagged array to matrix.
    • Parameters:
      • values: Jagged array to convert.
  • public static implicit operator Matrix<T>(T[,] values)

    • Implicitly converts 2D array to matrix.
    • Parameters:
      • values: 2D array to convert.

Operators

1. MatrixFp32 addition

  • public static Matrix<T> operator +(Matrix<T> a, Matrix<T> b)
    • MatrixFp32 addition operator.
    • Parameters:
      • a: First matrix.
      • b: Second matrix.
    • Returns: Sum of two matrices.

2. MatrixFp32 subtraction

  • public static Matrix<T> operator -(Matrix<T> a, Matrix<T> b)
    • MatrixFp32 subtraction operator.
    • Parameters:
      • a: First matrix.
      • b: Second matrix.
    • Returns: Difference of two matrices.

3. MatrixFp32 multiplication

  • public static Matrix<T> operator *(Matrix<T> a, Matrix<T> b)
    • MatrixFp32 multiplication operator.
    • Parameters:
      • a: First matrix.
      • b: Second matrix.
    • Returns: Product of two matrices.

4. MatrixFp32–scalar multiplication

  • public static Matrix<T> operator *(Matrix<T> matrix, T scalar)
    • MatrixFp32–scalar multiplication operator.
    • Parameters:
      • matrix: MatrixFp32.
      • scalar: Scalar.
    • Returns: MatrixFp32 times scalar.

5. MatrixFp32–scalar division

  • public static Matrix<T> operator /(Matrix<T> matrix, T scalar)
    • MatrixFp32–scalar division operator.
    • Parameters:
      • matrix: MatrixFp32.
      • scalar: Scalar.
    • Returns: MatrixFp32 divided by scalar.

Methods

1. GetRow

  • public Span<T> GetRow(int rowIndex)
    • Gets elements of the specified row.
    • Parameters:
      • rowIndex: Row index.
    • Returns: Span of row elements.

2. GetColumn

  • public T[] GetColumn(int columnIndex)
    • Gets elements of the specified column.
    • Parameters:
      • columnIndex: Column index.
    • Returns: T[] of column elements.

3. Transpose

  • public Matrix<T> Transpose()
    • Transposes the matrix.
    • Returns: Transposed matrix.

4. Determinant

  • public T Determinant()
    • Computes the matrix determinant.
    • Returns: Determinant.

5. Inverse

  • public Matrix<T> Inverse()
    • Computes the matrix inverse.
    • Returns: Inverse matrix.

6. LUDecomposition

  • public void LUDecomposition(out Matrix<T> L, out Matrix<T> U, out int[] P)
    • LU decomposition with partial pivoting.
    • Parameters:
      • L: Output lower triangular matrix.
      • U: Output upper triangular matrix.
      • P: Output pivot permutation array.

7. QRDecomposition

  • public void QRDecomposition(out Matrix<T> Q, out Matrix<T> R)
    • QR decomposition.
    • Parameters:
      • Q: Output orthogonal matrix.
      • R: Output upper triangular matrix.

8. CholeskyDecomposition

  • public Matrix<T> CholeskyDecomposition()
    • Cholesky decomposition.
    • Returns: Lower triangular matrix.

9. Eye

  • public static Matrix<T> Eye(int size)
    • Creates an identity matrix.
    • Parameters:
      • size: MatrixFp32 size (rows and columns).
    • Returns: Identity matrix.

10. Companion

  • public static Matrix<T> Companion(T[] a)
    • Creates a companion matrix.
    • Parameters:
      • a: Polynomial coefficients.
    • Returns: Companion matrix.
    • Exceptions:
      • ArgumentException: Thrown when coefficient array length < 2 or first coefficient is zero。

11. FillRandom

  • public void FillRandom()
    • Fills matrix with random values.

12. Clone

  • public Matrix<T> Clone()
    • Creates a deep copy.
    • Returns: Deep copy.

13. ToString

  • public override string ToString()
    • Returns string representation of matrix.
    • Returns: String representation.

Code example

The following example uses MatrixFp32<T> with comments:

using System; 
using Vorcyc.Mathematics.LinearAlgebra;

public class MatrixExample 
{ 
    public static void Main() 
    { 
        // Construct matrix from 2D array 
        Matrix<double> matrixA = new Matrix<double>(new double[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } });

        // Construct matrix by size
        Matrix<double> matrixB = new Matrix<double>(3, 3);
        matrixB.FillRandom();

        // MatrixFp32 addition
        Matrix<double> sum = matrixA + matrixB;
        Console.WriteLine("Sum of matrices:\n" + sum);

        // MatrixFp32 subtraction
        Matrix<double> difference = matrixA - matrixB;
        Console.WriteLine("Difference of matrices:\n" + difference);

        // MatrixFp32 multiplication
        Matrix<double> product = matrixA * matrixB;
        Console.WriteLine("Product of matrices:\n" + product);

        // Transpose
        Matrix<double> transpose = matrixA.Transpose();
        Console.WriteLine("Transpose of matrixA:\n" + transpose);

        // Determinant
        double determinant = matrixA.Determinant();
        Console.WriteLine("Determinant of matrixA: " + determinant);

        // Inverse
        Matrix<double> inverse = matrixA.Inverse();
        Console.WriteLine("Inverse of matrixA:\n" + inverse);

        // LU decomposition
        matrixA.LUDecomposition(out Matrix<double> L, out Matrix<double> U, out int[] P);
        Console.WriteLine("L matrix from LU decomposition:\n" + L);
        Console.WriteLine("U matrix from LU decomposition:\n" + U);

        // QR decomposition
        matrixA.QRDecomposition(out Matrix<double> Q, out Matrix<double> R);
        Console.WriteLine("Q matrix from QR decomposition:\n" + Q);
        Console.WriteLine("R matrix from QR decomposition:\n" + R);

        // Cholesky decomposition
        Matrix<double> cholesky = matrixA.CholeskyDecomposition();
        Console.WriteLine("Cholesky decomposition of matrixA:\n" + cholesky);

        // Identity matrix
        Matrix<double> identity = Matrix<double>.Eye(3);
        Console.WriteLine("Identity matrix:\n" + identity);

        // Companion matrix
        Matrix<double> companion = Matrix<double>.Companion(new double[] { 1.0, -6.0, 11.0, -6.0 });
        Console.WriteLine("Companion matrix:\n" + companion);

        // Deep copy
        Matrix<double> clone = matrixA.Clone();
        Console.WriteLine("Clone of matrixA:\n" + clone);
    }
}

Vorcyc.Mathematics.LinearAlgebra.MatrixHelper class

Vorcyc.Mathematics.LinearAlgebra.MatrixHelper is a static helper for matrix and array operations。

Methods

1. GetLength

  • internal static int GetLength<T>(T[][] values, int dimension)

    • Gets length of the specified dimension of a jagged array.
    • Parameters:
      • values: Jagged array。
      • dimension: Dimension (1 or 2)。
    • Returns: Length of dimension.
  • internal static int GetLength<T>(T[,] values, int dimension)

    • Gets length of the specified dimension of a 2D array.
    • Parameters:
      • values: 2D array。
      • dimension: Dimension (1 or 2)。
    • Returns: Length of dimension.

2. GetTotalLength

  • public static int GetTotalLength(this Array array, bool deep = true, bool rectangular = true)
    • Gets total length across all dimensions.
    • Parameters:
      • array: Array。
      • deep: Whether to recurse into all dimensions。
      • rectangular: Whether to assume a rectangular array。
    • Returns: Total length across all dimensions.

3. GetLength

  • public static int[] GetLength(this Array array, bool deep = true, bool max = false)
    • Gets length of each dimension.
    • Parameters:
      • array: Array。
      • deep: Whether to recurse into all dimensions。
      • max: Whether to use max length per dimension。
    • Returns: Length of each dimension.

4. IsJagged

  • public static bool IsJagged(this Array array)
    • Determines whether array is jagged.
    • Parameters:
      • array: Array。
    • Returns: true if jagged array.

5. IsMatrix

  • public static bool IsMatrix(this Array array)
    • Determines whether array is multidimensional.
    • Parameters:
      • array: Array。
    • Returns: true if multidimensional array.

6. IsVector

  • public static bool IsVector(this Array array)
    • Determines whether array is a vector.
    • Parameters:
      • array: Array。
    • Returns: true if vector.

7. Concatenate

  • public static T[] Concatenate<T>(this T[] a, params T[] b)

    • Horizontally concatenates two vectors.
    • Parameters:
      • a: First vector。
      • b: Second vector。
    • Returns: Concatenated vector.
  • public static T[] Concatenate<T>(this T[] vector, T element)

    • Horizontally concatenates vector and element.
    • Parameters:
      • vector: Vector。
      • element: Element。
    • Returns: Concatenated vector.
  • public static T[] Concatenate<T>(this T element, T[] vector)

    • Horizontally concatenates element and vector.
    • Parameters:
      • element: Element。
      • vector: Vector。
    • Returns: Concatenated vector.
  • public static T[,] Concatenate<T>(this T[,] a, T[,] b)

    • Horizontally concatenates two 2D arrays.
    • Parameters:
      • a: First 2D array。
      • b: Second 2D array。
    • Returns: Concatenated 2D array.
  • public static T[][] Concatenate<T>(this T[][] a, T[][] b)

    • Horizontally concatenates two jagged arrays.
    • Parameters:
      • a: First jagged array。
      • b: Second jagged array。
    • Returns: Concatenated jagged array.
  • public static T[,] Concatenate<T>(params T[][,] matrices)

    • Horizontally concatenates multiple 2D arrays.
    • Parameters:
      • matrices: Multiple 2D arrays。
    • Returns: Concatenated 2D array.
  • public static T[][] Concatenate<T>(params T[][][] matrices)

    • Horizontally concatenates multiple jagged arrays.
    • Parameters:
      • matrices: Multiple jagged arrays。
    • Returns: Concatenated jagged array.
  • public static T[] Concatenate<T>(this T[][] vectors)

    • Horizontally concatenates multiple vectors.
    • Parameters:
      • vectors: Multiple vectors。
    • Returns: Concatenated vector.

8. Stack

  • public static T[][] Stack<T>(this T[][] a, T[][] b)

    • Vertically stacks two jagged arrays.
    • Parameters:
      • a: First jagged array。
      • b: Second jagged array。
    • Returns: Concatenated jagged array.
  • public static T[,] Stack<T>(params T[] elements)

    • Vertically stacks multiple vectors.
    • Parameters:
      • elements: Multiple vectors。
    • Returns: Concatenated 2D array.
  • public static T[,] Stack<T>(this T[] vector, T element)

    • Vertically stacks vector and element.
    • Parameters:
      • vector: Vector。
      • element: Element。
    • Returns: Concatenated 2D array.
  • public static T[,] Stack<T>(params T[][,] matrices)

    • Vertically stacks multiple 2D arrays.
    • Parameters:
      • matrices: Multiple 2D arrays。
    • Returns: Concatenated 2D array.
  • public static T[,] Stack<T>(this T[,] matrix, T[] vector)

    • Vertically stacks 2D array and vector.
    • Parameters:
      • matrix: 2D array。
      • vector: Vector。
    • Returns: Concatenated 2D array.
  • public static T[][] Stack<T>(params T[][][] matrices)

    • Vertically stacks multiple jagged arrays.
    • Parameters:
      • matrices: Multiple jagged arrays。
    • Returns: Concatenated jagged array.

9. Transpose

  • public static T[,] Transpose<T>(this T[,] matrix)

    • Gets matrix transpose.
    • Parameters:
      • matrix: MatrixFp32.
    • Returns: Transposed matrix.
  • public static T[,] Transpose<T>(this T[,] matrix, bool inPlace)

    • Gets matrix transpose.
    • Parameters:
      • matrix: MatrixFp32.
      • inPlace: Whether to transpose in place。
    • Returns: Transposed matrix.
  • public static T[,] Transpose<T>(this T[] rowVector)

    • Gets transpose of row vector.
    • Parameters:
      • rowVector: Row vector。
    • Returns: Transposed matrix.
  • public static T[,] Transpose<T>(this T[] rowVector, T[,] result)

    • Gets transpose of row vector.
    • Parameters:
      • rowVector: Row vector。
      • result: MatrixFp32 to store transpose result。
    • Returns: Transposed matrix.
  • public static Array Transpose(this Array array, int[] order)

    • Gets generalized tensor transpose.
    • Parameters:
      • array: TensorFp32。
      • order: New dimension order。
    • Returns: Transposed tensor.
  • public static T Transpose<T>(this T array, int[] order) where T : class, IList

    • Gets generalized tensor transpose.
    • Parameters:
      • array: TensorFp32。
      • order: New dimension order。
    • Returns: Transposed tensor.

10. Get

  • public static T[,] Get<T>(this T[,] source, int startRow, int endRow, int startColumn, int endColumn)

    • Returns extracted submatrix.
    • Parameters:
      • source: Source matrix。
      • startRow: Start row index。
      • endRow: End row index。
      • startColumn: Start column index。
      • endColumn: End column index。
    • Returns: Extracted submatrix.
  • public static T[,] Get<T>(this T[,] source, T[,] destination, int startRow, int endRow, int startColumn, int endColumn)

    • Returns extracted submatrix.
    • Parameters:
      • source: Source matrix。
      • destination: MatrixFp32 to store result。
      • startRow: Start row index。
      • endRow: End row index。
      • startColumn: Start column index。
      • endColumn: End column index。
    • Returns: Extracted submatrix.
  • public static T[,] Get<T>(this T[,] source, int[] rowIndexes, int[] columnIndexes, T[,] result = null)

    • Returns extracted submatrix.
    • Parameters:
      • source: Source matrix。
      • rowIndexes: Row index array。
      • columnIndexes: Column index array。
      • result: MatrixFp32 to store result。
    • Returns: Extracted submatrix.
  • public static T[,] Get<T>(this T[,] source, bool[] rowMask, bool[] columnMask, T[,] result = null)

    • Returns extracted submatrix.
    • Parameters:
      • source: Source matrix。
      • rowMask: Row mask array。
      • columnMask: Column mask array。
      • result: MatrixFp32 to store result。
    • Returns: Extracted submatrix.
  • public static T[,] Get<T>(this T[,] source, int[] rowIndexes)

    • Returns extracted submatrix.
    • Parameters:
      • source: Source matrix。
      • rowIndexes: Row index array。
    • Returns: Extracted submatrix.
  • public static T[,] Get<T>(this T[,] source, int startRow, int endRow, int[] columnIndexes)

    • Returns extracted submatrix.
    • Parameters:
      • source: Source matrix。
      • startRow: Start row index。
      • endRow: End row index。
      • columnIndexes: Column index array。
    • Returns: Extracted submatrix.
  • public static T[,] Get<T>(this T[,] source, int[] rowIndexes, int startColumn, int endColumn)

    • Returns extracted submatrix.
    • Parameters:
      • source: Source matrix。
      • rowIndexes: Row index array。
      • startColumn: Start column index。
      • endColumn: End column index。
    • Returns: Extracted submatrix.
  • public static T[][] Get<T>(this T[][] source, int startRow, int endRow, int startColumn, int endColumn)

    • Returns extracted subarray from jagged array.
    • Parameters:
      • source: Source jagged array。
      • startRow: Start row index。
      • endRow: End row index。
      • startColumn: Start column index。
      • endColumn: End column index。
    • Returns: Extracted subarray.
  • public static T[][] Set<T>(this T[][] destination, int startRow, int endRow, int startColumn, int endColumn, T[][] values)

    • Sets matrix submatrix.
    • Parameters:
      • destination: Destination matrix。
      • startRow: Start row index。
      • endRow: End row index。
      • startColumn: Start column index。
      • endColumn: End column index。
      • values: Submatrix values。
    • Returns: MatrixFp32 after set.
  • public static T[][] Set<T>(this T[][] values, Func<T, bool> match, T value)

    • Sets matching elements in matrix.
    • Parameters:
      • values: MatrixFp32。
      • match: Function that decides whether to change elements。
      • value: Value to set。
    • Returns: MatrixFp32 after set.
  • public static T[][] Get<T>(this T[][] source, int[] rowIndexes, int[] columnIndexes, bool reuseMemory = false, T[][] result = null)

    • Returns extracted subarray from jagged array.
    • Parameters:
      • source: Source jagged array。
      • rowIndexes: Row index array。
      • columnIndexes: Column index array。
      • reuseMemory: Whether to reuse memory。
      • result: Array to store result。
    • Returns: Extracted subarray.
  • public static T[][] Get<T>(this T[][] source, bool[] rowMask, bool[] columnMask, bool reuseMemory = false, T[][] result = null)

    • Returns extracted subarray from jagged array.
    • Parameters:
      • source: Source jagged array。
      • rowMask: Row mask array。
      • columnMask: Column mask array。
      • reuseMemory: Whether to reuse memory。
      • result: Array to store result。
    • Returns: Extracted subarray.
  • public static T[][] Get<T>(this T[][] source, int[] indexes, bool transpose = false)

    • Returns extracted subarray from jagged array.
    • Parameters:
      • source: Source jagged array。
      • indexes: Index array。
      • transpose: Whether to transpose the result。
    • Returns: Extracted subarray.
  • public static T[][] Get<T>(this T[][] source, int startRow, int endRow, int[] columnIndexes)

    • Returns extracted subarray from jagged array.
    • Parameters:
      • source: Source jagged array。
      • startRow: Start row index。
      • endRow: End row index。
      • columnIndexes: Column index array。
    • Returns: Extracted subarray.
  • public static T[] Get<T>(this T[] source, int[] indexes, bool inPlace = false)

    • Returns extracted subvector.
    • Parameters:
      • source: Source vector。
      • indexes: Index array。
      • inPlace: Whether to operate in place on the vector。
    • Returns: Extracted subvector.
  • public static T[] Get<T>(this T[] source, IList<int> indexes)

    • Returns extracted subvector.
    • Parameters:
      • source: Source vector。
      • indexes: Index list。
    • Returns: Extracted subvector.
  • public static T[] Get<T>(this T[] source, int startRow, int endRow)

    • Returns extracted subvector.
    • Parameters:
      • source: Source vector。
      • startRow: Start row index。
      • endRow: End row index。
    • Returns: Extracted subvector.
  • public static T Get<T>(this T[] source, int index)

    • Returns extracted value from vector.
    • Parameters:
      • source: Source vector。
      • index: Index。
    • Returns: Extracted value.
  • public static List<T> Get<T>(this List<T> source, int[] indexes)

    • Returns extracted sublist.
    • Parameters:
      • source: Source list。
      • indexes: Index array。
    • Returns: Extracted sublist.

11. Rows

  • public static int Rows<T>(this T[] vector)

    • Gets vector row count.
    • Parameters:
      • vector: Vector。
    • Returns: Vector row count.
  • public static int Rows<T>(this T[,] matrix)

    • Gets row count.
    • Parameters:
      • matrix: MatrixFp32.
    • Returns: Row count.

12. Columns

  • public static int Columns<T>(this T[,] matrix)
    • Gets column count.
    • Parameters:
      • matrix: MatrixFp32.
    • Returns: Column count.

13. Count

  • public static int Count<T>(this T[] data, Func<T, bool> func)
    • Gets count of matching elements.
    • Parameters:
      • data: Array。
      • func: Predicate function。
    • Returns: Count of matching elements.

14. First

  • public static int First<T>(this T[] data, Func<T, bool> func)
    • Gets index of first matching element.
    • Parameters:
      • data: Array。
      • func: Predicate function。
    • Returns: First matching index.

15. FirstOrNull

  • public static int? FirstOrNull<T>(this T[] data, Func<T, bool> func)
    • Gets first matching index, or null.
    • Parameters:
      • data: Array。
      • func: Predicate function。
    • Returns: First matching index, or null.

16. IndexOf

  • public static int IndexOf<T>(this T[] data, T value)
    • Searches value; returns first index.
    • Parameters:
      • data: Array。
      • value: Value to search for。
    • Returns: Index of value, or -1.

17. Find

  • public static int[] Find<T>(this T[] data, Func<T, bool> func)

    • Gets indexes of all matching elements.
    • Parameters:
      • data: Array。
      • func: Predicate function。
    • Returns: Indexes of matching elements.
  • public static int[] Find<T>(this T[] data, Func<T, bool> func, bool firstOnly)

    • Gets indexes of all matching elements.
    • Parameters:
      • data: Array。
      • func: Predicate function。
      • firstOnly: Whether to return only the first matching index。
    • Returns: Indexes of matching elements.
  • public static int[][] Find<T>(this T[,] data, Func<T, bool> func)

    • Gets indexes of all matching elements.
    • Parameters:
      • data: 2D array。
      • func: Predicate function。
    • Returns: Indexes of matching elements.
  • public static int[][] Find<T>(this T[,] data, Func<T, bool> func, bool firstOnly)

    • Gets indexes of all matching elements.
    • Parameters:
      • data: 2D array。
      • func: Predicate function。
      • firstOnly: Whether to return only the first matching index。
    • Returns: Indexes of matching elements.

Code example

The following example uses MatrixHelper with comments:

using System; 
using Vorcyc.Mathematics.LinearAlgebra;

public class MatrixHelperExample 
{ 
    public static void Main() 
    { 
        // 2D array
        int[,] matrix = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

        // Get matrix transpose
        int[,] transpose = matrix.Transpose();
        Console.WriteLine("Transpose of matrix:");
        PrintMatrix(transpose);

        // Get submatrix
        int[,] subMatrix = matrix.Get(0, 2, 0, 2);
        Console.WriteLine("SubMatrix of matrix:");
        PrintMatrix(subMatrix);

        // Combine two matrices
        int[,] concatenatedMatrix = matrix.Concatenate(matrix);
        Console.WriteLine("Concatenated matrix:");
        PrintMatrix(concatenatedMatrix);

        // Get indexes of matching elements
        int[][] indices = matrix.Find(x => x > 5);
        Console.WriteLine("Indices of elements greater than 5:");
        foreach (var index in indices)
        {
            Console.WriteLine($"({index[0]}, {index[1]})");
        }
    }

    private static void PrintMatrix(int[,] matrix)
    {
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}

Vorcyc.Mathematics.LinearAlgebra.MatrixOperations class

Vorcyc.Mathematics.LinearAlgebra.MatrixOperations is a static class of matrix operations。

Methods

1. Multiply

  • public static T[,] Multiply<T>(T[,] a, T[,] b) where T : INumber<T>

    • Multiplication operator for two matrices.
    • Parameters:
      • a: First matrix.
      • b: Second matrix.
    • Returns: Product of two matrices.
    • Exceptions:
      • ArgumentException: Thrown when matrix dimensions are incompatible。
  • public static float[][] Multiply(float[][] a, float[][] b)

    • Multiplication operator for two jagged matrices.
    • Parameters:
      • a: First jagged matrix。
      • b: Second jagged matrix。
    • Returns: Product of two jagged matrices.
    • Exceptions:
      • ArgumentException: Thrown when matrix dimensions are incompatible。

Code example

The following example uses MatrixOperations.Multiply with comments:

using System; 
using Vorcyc.Mathematics.LinearAlgebra;

public class MatrixOperationsExample 
{ 
    public static void Main() 
    { 
        // Two 2D array matrices
        int[,] matrixA = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        int[,] matrixB = new int[,]
        {
            { 9, 8, 7 },
            { 6, 5, 4 },
            { 3, 2, 1 }
        };

        // MatrixFp32 multiplication
        int[,] product = MatrixOperations.Multiply(matrixA, matrixB);
        Console.WriteLine("Product of matrixA and matrixB:");
        PrintMatrix(product);

        // Two jagged matrices
        float[][] jaggedMatrixA = new float[][]
        {
            new float[] { 1.0f, 2.0f, 3.0f },
            new float[] { 4.0f, 5.0f, 6.0f },
            new float[] { 7.0f, 8.0f, 9.0f }
        };

        float[][] jaggedMatrixB = new float[][]
        {
            new float[] { 9.0f, 8.0f, 7.0f },
            new float[] { 6.0f, 5.0f, 4.0f },
            new float[] { 3.0f, 2.0f, 1.0f }
        };

        // Jagged matrix multiply
        float[][] jaggedProduct = MatrixOperations.Multiply(jaggedMatrixA, jaggedMatrixB);
        Console.WriteLine("Product of jaggedMatrixA and jaggedMatrixB:");
        PrintJaggedMatrix(jaggedProduct);
    }

    private static void PrintMatrix(int[,] matrix)
    {
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }
    }

    private static void PrintJaggedMatrix(float[][] matrix)
    {
        for (int i = 0; i < matrix.Length; i++)
        {
            for (int j = 0; j < matrix[i].Length; j++)
            {
                Console.Write(matrix[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}

Vorcyc.Mathematics.LinearAlgebra.Quaternion<T> struct

Vorcyc.Mathematics.LinearAlgebra.Quaternion<T> is a generic quaternion struct with basic operations。

Properties

1. W

  • public T W { get; }
    • Gets quaternion W component.

2. X

  • public T X { get; }
    • Gets quaternion X component.

3. Y

  • public T Y { get; }
    • Gets quaternion Y component.

4. Z

  • public T Z { get; }
    • Gets quaternion Z component.

Constructors

1. Quaternion<T>(T w, T x, T y, T z)

  • public Quaternion<T>(T w, T x, T y, T z)
    • Constructs quaternion from components.
    • Parameters:
      • w: W component。
      • x: X component。
      • y: Y component。
      • z: Z component。

Methods

1. Conjugate

  • public Quaternion<T> Conjugate()
    • Returns quaternion conjugate.
    • Returns: Quaternion conjugate.

2. Norm

  • public T Norm()
    • Returns quaternion norm.
    • Returns: Quaternion norm.

3. Normalize

  • public Quaternion<T> Normalize()
    • Returns normalized quaternion.
    • Returns: Normalized quaternion.

4. Inverse

  • public Quaternion<T> Inverse()
    • Returns quaternion inverse.
    • Returns: Quaternion inverse.

Operators

1. Addition operator

  • public static Quaternion<T> operator +(Quaternion<T> a, Quaternion<T> b)
    • Addition operator for two quaternions.
    • Parameters:
      • a: First quaternion。
      • b: Second quaternion。
    • Returns: Sum of two quaternions.

2. Subtraction operator

  • public static Quaternion<T> operator -(Quaternion<T> a, Quaternion<T> b)
    • Subtraction operator for one quaternion minus another.
    • Parameters:
      • a: First quaternion。
      • b: Second quaternion。
    • Returns: Difference of two quaternions.

3. Multiplication operator

  • public static Quaternion<T> operator *(Quaternion<T> a, Quaternion<T> b)
    • Multiplication operator for two quaternions.
    • Parameters:
      • a: First quaternion。
      • b: Second quaternion。
    • Returns: Product of two quaternions.

4. Division operator

  • public static Quaternion<T> operator /(Quaternion<T> a, Quaternion<T> b)
    • Division operator for one quaternion divided by another.
    • Parameters:
      • a: First quaternion。
      • b: Second quaternion。
    • Returns: Quotient of two quaternions.

5. Equality operator

  • public static bool operator ==(Quaternion<T> left, Quaternion<T> right)
    • Equality operator for two quaternions.
    • Parameters:
      • left: First quaternion。
      • right: Second quaternion。
    • Returns: true if quaternions are equal.

6. Inequality operator

  • public static bool operator !=(Quaternion<T> left, Quaternion<T> right)
    • Inequality operator for two quaternions.
    • Parameters:
      • left: First quaternion。
      • right: Second quaternion。
    • Returns: true if quaternions are not equal.

Overrides

1. ToString

  • public override string ToString()
    • Returns string representation.
    • Returns: String representation.

2. Equals

  • public override bool Equals(object? obj)
    • Determines whether object equals this quaternion.
    • Parameters:
      • obj: Object to compare with this quaternion。
    • Returns: true if object equals this quaternion.

3. GetHashCode

  • public override int GetHashCode()
    • Returns hash code.
    • Returns: Hash code.

Code example

The following example uses several Quaternion methods with comments:

using System; 
using Vorcyc.Mathematics.LinearAlgebra;

public class QuaternionExample 
{ 
    public static void Main() 
    { 
        // Quaternions
        Quaternion<double> quaternionA = new Quaternion<double>(1.0, 2.0, 3.0, 4.0); 
        Quaternion<double> quaternionB = new Quaternion<double>(5.0, 6.0, 7.0, 8.0);
        // Quaternion addition
        Quaternion<double> sum = quaternionA + quaternionB;
        Console.WriteLine("Sum of quaternionA and quaternionB: " + sum);

        // Quaternion subtraction
        Quaternion<double> difference = quaternionA - quaternionB;
        Console.WriteLine("Difference of quaternionA and quaternionB: " + difference);

        // Quaternion multiplication
        Quaternion<double> product = quaternionA * quaternionB;
        Console.WriteLine("Product of quaternionA and quaternionB: " + product);

        // Quaternion division
        Quaternion<double> quotient = quaternionA / quaternionB;
        Console.WriteLine("Quotient of quaternionA and quaternionB: " + quotient);

        // Quaternion conjugate
        Quaternion<double> conjugate = quaternionA.Conjugate();
        Console.WriteLine("Conjugate of quaternionA: " + conjugate);

        // Quaternion norm
        double norm = quaternionA.Norm();
        Console.WriteLine("Norm of quaternionA: " + norm);

        // Quaternion normalization
        Quaternion<double> normalized = quaternionA.Normalize();
        Console.WriteLine("Normalized quaternionA: " + normalized);

        // Quaternion inverse
        Quaternion<double> inverse = quaternionA.Inverse();
        Console.WriteLine("Inverse of quaternionA: " + inverse);
    }
}

Vorcyc.Mathematics.LinearAlgebra.TensorFp32 class

Vorcyc.Mathematics.LinearAlgebra.TensorFp32 is a 3D tensor with basic operations。

Properties

1. Values

  • public float[] Values { get; }
    • Gets tensor values.

2. Width

  • public int Width { get; }
    • Gets tensor width.

3. Height

  • public int Height { get; }
    • Gets tensor height.

4. Depth

  • public int Depth { get; }
    • Gets tensor depth.

Constructors

1. TensorFp32(int w, int h, int d)

  • public TensorFp32(int w, int h, int d)
    • Initializes tensor with given size.
    • Parameters:
      • w: Width。
      • h: Height。
      • d: Depth。

2. TensorFp32(int w, int h, int d, float initialValue)

  • public TensorFp32(int w, int h, int d, float initialValue)
    • Initializes tensor with size and initial value.
    • Parameters:
      • w: Width。
      • h: Height。
      • d: Depth。
      • initialValue: Initial value for all elements。

3. TensorFp32(float[,,] array)

  • public TensorFp32(float[,,] array)
    • Initializes tensor from 3D array.
    • Parameters:
      • array: 3D array used to initialize the tensor。

Indexers

1. this[int x, int y, int z]

  • public ref float this[int x, int y, int z]
    • Gets or sets value at coordinates.
    • Parameters:
      • x: X coordinate (width)。
      • y: Y coordinate (height)。
      • z: Z coordinate (depth)。
    • Returns: Value at coordinates.

Methods

1. Fill

  • public void Fill(float value)
    • Fills tensor with value.
    • Parameters:
      • value: Value to fill the tensor with。

2. Add

  • public void Add(TensorFp32 other)
    • Adds another tensor to this tensor.
    • Parameters:
      • other: TensorFp32 to add。

3. Subtract

  • public void Subtract(TensorFp32 other)
    • Subtracts another tensor from this tensor.
    • Parameters:
      • other: TensorFp32 to subtract。

4. Multiply

  • public void Multiply(float scalar)
    • Multiplies this tensor by a scalar.
    • Parameters:
      • scalar: Scalar multiplier。

5. Transpose

  • public TensorFp32 Transpose(int axis1, int axis2)
    • Transposes tensor along axes.
    • Parameters:
      • axis1: First axis。
      • axis2: Second axis。
    • Returns: New transposed tensor.

6. Sum

  • public float Sum()
    • Computes the sum of all tensor elements.
    • Returns: Sum of all tensor elements.

7. Dot

  • public float Dot(TensorFp32 other)
    • Computes the dot product of two tensors.
    • Parameters:
      • other: Other tensor。
    • Returns: Dot product of two tensors.

8. Normalize

  • public void Normalize()
    • normalizationTensor。

9. Norm

  • public float Norm()
    • Computes the tensor norm.
    • Returns: TensorFp32 norm.

10. Slice

  • public TensorFp32 Slice(int axis, int index)
    • Slices tensor along axis.
    • Parameters:
      • axis: Axis to slice along。
      • index: Slice index。
    • Returns: Sliced tensor.

11. Clone

  • public TensorFp32 Clone()
    • Clones tensor.
    • Returns: A new tensor copy.

Operators

1. Addition operator

  • public static TensorFp32 operator +(TensorFp32 a, TensorFp32 b)
    • Addition operator for two tensors.
    • Parameters:
      • a: First tensor。
      • b: Second tensor。
    • Returns: Sum of two tensors.

2. Subtraction operator

  • public static TensorFp32 operator -(TensorFp32 a, TensorFp32 b)
    • Subtraction operator for one tensor minus another.
    • Parameters:
      • a: First tensor。
      • b: Second tensor。
    • Returns: Difference of two tensors.

3. Multiplication operator

  • public static TensorFp32 operator *(TensorFp32 tensor, float scalar)

    • Multiplication operator for tensor times scalar.
    • Parameters:
      • tensor: TensorFp32。
      • scalar: Scalar value。
    • Returns: TensorFp32 times scalar.
  • public static TensorFp32 operator *(float scalar, TensorFp32 tensor)

    • Multiplication operator for tensor times scalar.
    • Parameters:
      • scalar: Scalar value。
      • tensor: TensorFp32。
    • Returns: TensorFp32 times scalar.

4. Equality operator

  • public static bool operator ==(TensorFp32 a, TensorFp32 b)
    • Equality operator for two tensors.
    • Parameters:
      • a: First tensor。
      • b: Second tensor。
    • Returns: true if tensors are equal.

5. Inequality operator

  • public static bool operator !=(TensorFp32 a, TensorFp32 b)
    • Inequality operator for two tensors.
    • Parameters:
      • a: First tensor。
      • b: Second tensor。
    • Returns: true if tensors are not equal.

Overrides

1. ToString

  • public override string ToString()
    • Returns string representation of tensor.
    • Returns: String representation.

2. Equals

  • public override bool Equals(object? obj)
    • Determines whether object equals this tensor.
    • Parameters:
      • obj: Object to compare with this tensor。
    • Returns: true if object equals this tensor.

3. GetHashCode

  • public override int GetHashCode()
    • Returns hash code.
    • Returns: Hash code.

Code example

The following example uses TensorFp32 with comments:

using System; 
using Vorcyc.Mathematics.LinearAlgebra;

public class TensorExample 
{
    public static void Main()
    { 
        // TensorFp32
        TensorFp32 tensorA = new TensorFp32(2, 2, 2, 1.0f); 
        TensorFp32 tensorB = new TensorFp32(new float[,,] { { { 1.0f, 2.0f }, { 3.0f, 4.0f } }, { { 5.0f, 6.0f }, { 7.0f, 8.0f } } });

        // TensorFp32 add
        TensorFp32 sum = tensorA + tensorB;
        Console.WriteLine("Sum of tensorA and tensorB: " + sum);

        // TensorFp32 subtract
        TensorFp32 difference = tensorA - tensorB;
        Console.WriteLine("Difference of tensorA and tensorB: " + difference);

        // TensorFp32 multiply
        TensorFp32 product = tensorA * 2.0f;
        Console.WriteLine("Product of tensorA and scalar: " + product);

        // Transpose tensor
        TensorFp32 transposed = tensorB.Transpose(0, 1);
        Console.WriteLine("Transposed tensorB: " + transposed);

        // TensorFp32 sum
        float sumOfElements = tensorB.Sum();
        Console.WriteLine("Sum of elements in tensorB: " + sumOfElements);

        // TensorFp32 dot product
        float dotProduct = tensorA.Dot(tensorB);
        Console.WriteLine("Dot product of tensorA and tensorB: " + dotProduct);

        // Normalize tensor
        tensorB.Normalize();
        Console.WriteLine("Normalized tensorB: " + tensorB);

        // TensorFp32 norm
        float norm = tensorB.Norm();
        Console.WriteLine("Norm of tensorB: " + norm);

        // TensorFp32 slice
        TensorFp32 slice = tensorB.Slice(0, 1);
        Console.WriteLine("Slice of tensorB along axis 0 at index 1: " + slice);

        // Clone tensor
        TensorFp32 clone = tensorB.Clone();
        Console.WriteLine("Clone of tensorB: " + clone);
    }
}

Vorcyc.Mathematics.LinearAlgebra.TensorFp32<T> class

Vorcyc.Mathematics.LinearAlgebra.TensorFp32<T> is a generic 3D tensor with basic operations。

Properties

1. Values

  • public Span<T> Values { get; }
    • Gets tensor values.

2. Width

  • public int Width { get; }
    • Gets tensor width.

3. Height

  • public int Height { get; }
    • Gets tensor height.

4. Depth

  • public int Depth { get; }
    • Gets tensor depth.

Constructors

1. TensorFp32(int w, int h, int d)

  • public TensorFp32(int w, int h, int d)
    • Initializes tensor with given size.
    • Parameters:
      • w: Width。
      • h: Height。
      • d: Depth。

2. TensorFp32(int w, int h, int d, T initialValue)

  • public TensorFp32(int w, int h, int d, T initialValue)
    • Initializes tensor with size and initial value.
    • Parameters:
      • w: Width。
      • h: Height。
      • d: Depth。
      • initialValue: Initial value for all elements。

3. TensorFp32(T[,,] array)

  • public TensorFp32(T[,,] array)
    • Initializes tensor from 3D array.
    • Parameters:
      • array: 3D array used to initialize the tensor。

Indexers

1. this[int x, int y, int z]

  • public ref T this[int x, int y, int z]
    • Gets or sets value at coordinates.
    • Parameters:
      • x: X coordinate (width)。
      • y: Y coordinate (height)。
      • z: Z coordinate (depth)。
    • Returns: Value at coordinates.

Methods

1. Fill

  • public void Fill(T value)
    • Fills tensor with value.
    • Parameters:
      • value: Value to fill the tensor with。

2. Add

  • public void Add(Tensor<T> other)
    • Adds another tensor to this tensor.
    • Parameters:
      • other: TensorFp32 to add。

3. Subtract

  • public void Subtract(Tensor<T> other)
    • Subtracts another tensor from this tensor.
    • Parameters:
      • other: TensorFp32 to subtract。

4. Multiply

  • public void Multiply(T scalar)
    • Multiplies this tensor by a scalar.
    • Parameters:
      • scalar: Scalar multiplier。

5. Transpose

  • public Tensor<T> Transpose(int axis1, int axis2)
    • Transposes tensor along axes.
    • Parameters:
      • axis1: First axis。
      • axis2: Second axis。
    • Returns: New transposed tensor.

6. Sum

  • public T Sum()
    • Computes the sum of all tensor elements.
    • Returns: Sum of all tensor elements.

7. Dot

  • public T Dot(Tensor<T> other)
    • Computes the dot product of two tensors.
    • Parameters:
      • other: Other tensor。
    • Returns: Dot product of two tensors.

8. Normalize

  • public void Normalize()
    • normalizationTensor。

9. Norm

  • public T Norm()
    • Computes the tensor norm.
    • Returns: TensorFp32 norm.

10. Slice

  • public Tensor<T> Slice(int axis, int index)
    • Slices tensor along axis.
    • Parameters:
      • axis: Axis to slice along。
      • index: Slice index。
    • Returns: Sliced tensor.

11. Clone

  • public Tensor<T> Clone()
    • Clones tensor.
    • Returns: A new tensor copy.

Operators

1. Addition operator

  • public static Tensor<T> operator +(Tensor<T> a, Tensor<T> b)
    • Addition operator for two tensors.
    • Parameters:
      • a: First tensor。
      • b: Second tensor。
    • Returns: Sum of two tensors.

2. Subtraction operator

  • public static Tensor<T> operator -(Tensor<T> a, Tensor<T> b)
    • Subtraction operator for one tensor minus another.
    • Parameters:
      • a: First tensor。
      • b: Second tensor。
    • Returns: Difference of two tensors.

3. Multiplication operator

  • public static Tensor<T> operator *(Tensor<T> tensor, T scalar)

    • Multiplication operator for tensor times scalar.
    • Parameters:
      • tensor: TensorFp32。
      • scalar: Scalar value。
    • Returns: TensorFp32 times scalar.
  • public static Tensor<T> operator *(T scalar, Tensor<T> tensor)

    • Multiplication operator for tensor times scalar.
    • Parameters:
      • scalar: Scalar value。
      • tensor: TensorFp32。
    • Returns: TensorFp32 times scalar.

4. Equality operator

  • public static bool operator ==(Tensor<T> a, Tensor<T> b)
    • Equality operator for two tensors.
    • Parameters:
      • a: First tensor。
      • b: Second tensor。
    • Returns: true if tensors are equal.

5. Inequality operator

  • public static bool operator !=(Tensor<T> a, Tensor<T> b)
    • Inequality operator for two tensors.
    • Parameters:
      • a: First tensor。
      • b: Second tensor。
    • Returns: true if tensors are not equal.

Overrides

1. ToString

  • public override string ToString()
    • Returns string representation of tensor.
    • Returns: String representation.

2. Equals

  • public override bool Equals(object? obj)
    • Determines whether object equals this tensor.
    • Parameters:
      • obj: Object to compare with this tensor。
    • Returns: true if object equals this tensor.

3. GetHashCode

  • public override int GetHashCode()
    • Returns hash code.
    • Returns: Hash code.

Code example

The following example uses TensorFp32<T> with comments:

using System; 
using Vorcyc.Mathematics.LinearAlgebra;

public class TensorExample 
{ 
    public static void Main() 
    { 
        // TensorFp32
        Tensor<double> tensorA = new Tensor<double>(2, 2, 2, 1.0); 
        Tensor<double> tensorB = new Tensor<double>(new double[,,] { { { 1.0, 2.0 }, { 3.0, 4.0 } }, { { 5.0, 6.0 }, { 7.0, 8.0 } } });

        // TensorFp32 add
        Tensor<double> sum = tensorA + tensorB;
        Console.WriteLine("Sum of tensorA and tensorB: " + sum);

        // TensorFp32 subtract
        Tensor<double> difference = tensorA - tensorB;
        Console.WriteLine("Difference of tensorA and tensorB: " + difference);

        // TensorFp32 multiply
        Tensor<double> product = tensorA * 2.0;
        Console.WriteLine("Product of tensorA and scalar: " + product);

        // Transpose tensor
        Tensor<double> transposed = tensorB.Transpose(0, 1);
        Console.WriteLine("Transposed tensorB: " + transposed);

        // TensorFp32 sum
        double sumOfElements = tensorB.Sum();
        Console.WriteLine("Sum of elements in tensorB: " + sumOfElements);

        // TensorFp32 dot product
        double dotProduct = tensorA.Dot(tensorB);
        Console.WriteLine("Dot product of tensorA and tensorB: " + dotProduct);

        // Normalize tensor
        tensorB.Normalize();
        Console.WriteLine("Normalized tensorB: " + tensorB);

        // TensorFp32 norm
        double norm = tensorB.Norm();
        Console.WriteLine("Norm of tensorB: " + norm);

        // TensorFp32 slice
        Tensor<double> slice = tensorB.Slice(0, 1);
        Console.WriteLine("Slice of tensorB along axis 0 at index 1: " + slice);

        // Clone tensor
        Tensor<double> clone = tensorB.Clone();
        Console.WriteLine("Clone of tensorB: " + clone);
    }
}

Vorcyc.Mathematics.LinearAlgebra.VectorSpan class

VectorSpan is a static utility. Math vectors use ReadOnlySpan<T>, Span<T>, or T[], avoiding confusion with BCL System.Numerics.Vector<T> (SIMD registers).

Methods

  • public static T Dot<T>(ReadOnlySpan<T> a, ReadOnlySpan<T> b) — dot product
  • public static T Norm<T>(ReadOnlySpan<T> vector) — Euclidean norm
  • public static void Add<T>(ReadOnlySpan<T> a, ReadOnlySpan<T> b, Span<T> result) — vector addition
  • public static void Subtract<T>(ReadOnlySpan<T> a, ReadOnlySpan<T> b, Span<T> result) — vector subtraction
  • public static void Scale<T>(ReadOnlySpan<T> vector, T scalar, Span<T> result) — scalar multiplication
  • public static void Normalize<T>(ReadOnlySpan<T> vector, Span<T> result) — normalization

For matrix–column-vector multiply use Matrix<T>.Multiply(ReadOnlySpan<T>) or Multiply(vector, result).

Code example

using Vorcyc.Mathematics.LinearAlgebra;

double[] a = { 1.0, 2.0, 3.0 };
double[] b = { 4.0, 5.0, 6.0 };
double[] sum = new double[3];
double[] product = new double[2];

VectorSpan.Add(a, b, sum);
double dot = VectorSpan.Dot(a, b);

var matrix = new Matrix<double>(new double[,] { { 1, 2, 3 }, { 4, 5, 6 } });
matrix.Multiply(a, product);

Vorcyc.Mathematics.LinearAlgebra.MatrixDecomposition class

MatrixDecomposition provides symmetric eigendecomposition and thin SVD。

  • Small matrices (min(m,n) ≤ 48 and m·n ≤ 256): QR + one-sided Jacobi (on R)
  • Large matrices: Golub–Kahan bidiagonalization + implicit QR (Golub–Reinsch); fallback to k×k Jacobi SVD when not converged

Methods

  • SymmetricEigendecomposition<T>(Matrix<T> matrix, T? tolerance = null, int maxIterations = 100) — Jacobi symmetric eigendecomposition; eigenvectors in columns of result matrix, sorted by eigenvalue descending
  • SingularValueDecomposition<T>(Matrix<T> matrix, T? tolerance = null) — thin SVD: A ≈ U·diag(Σ)·Vᵀ, k = min(m, n)
  • SingularValueDecomposition<T>(Matrix<T> matrix, T? tolerance, ComputingContext? context, CancellationToken cancellationToken = default) — same; Householder apply + factor combine honor ComputingContext; bidiagonal QR iteration stays sequential (cancel polled each sweep)
  • Pseudoinverse<T>(Matrix<T> matrix, T? tolerance = null) — Moore–Penrose pseudoinverse A⁺
  • Reconstruct<T>(SingularValueDecompositionResult<T> svd) — reconstruct A from U, Σ, Vᵀ

Code example

using Vorcyc.Mathematics;
using Vorcyc.Mathematics.LinearAlgebra;

var symmetric = new Matrix<double>(new double[,] { { 2, 1 }, { 1, 2 } });
var eig = MatrixDecomposition.SymmetricEigendecomposition(symmetric);

var design = new Matrix<double>(new double[,]
{
    { 1, 1 },
    { 1, 2 },
    { 1, 3 }
});
var svd = MatrixDecomposition.SingularValueDecomposition(design, tolerance: null, ComputingContext.Parallel);
var x = LinearEquationSolver.SolveLeastSquaresSvd(design, new double[] { 6, 8, 10 });

Vorcyc.Mathematics.LinearAlgebra.MatrixDiagnostics class

MatrixFp32 numerical diagnostics utilities.

Methods

  • ConditionNumber<T>(Matrix<T> matrix, T? tolerance = null) — estimated from thin SVD κ₂(A) ≈ σ_max / σ_min
  • IsIllConditioned<T>(Matrix<T> matrix, T threshold, T? tolerance = null) — whether condition number exceeds threshold
  • IsSymmetric<T>(Matrix<T> matrix, T? tolerance = null) — whether square matrix is symmetric within tolerance

Matrix<T> also provides instance methods: ConditionNumber(), IsIllConditioned(threshold), IsSymmetric(), and linear solvers: Solve(b), Solve(b, x), SolveSymmetricPositiveDefinite(b), SolveLeastSquares(y), SolveLeastSquaresSvd(y), SolveRidgeLeastSquares(y, lambda).

Legacy single-precision MatrixFp32 (MatrixFp32.cs) exposes the same solve/diagnostics APIs and interoperates with Matrix<float> via ToGeneric() / implicit conversion.

Vorcyc.Mathematics.LinearAlgebra.Tensor4D<T> class

Layout-neutral 4D tensor (Dim0–Dim3) with contiguous Memory<T> storage. Deep learning BatchTensor<T> maps N→Dim0, H→Dim1, W→Dim2, C→Dim3 onto the same storage.

Notes

  • Tensor4DShape — shape and ElementCount
  • Indexer [d0, d1, d2, d3] and GetLinearIndex
  • Fill and other batch operations

Vorcyc.Mathematics.LinearAlgebra.TensorOps class

NHWC tensor layout utilities reused by convolution im2col paths.

Methods

  • ConvolutionSamePadding / ConvolutionOutputSize — padding and output size consistent with in-library batch convolution
  • Im2ColNhwc — NHWC expand to (numPatches × patchSize) column matrix
  • Col2ImNhwc — scatter column matrix back to NHWC gradient (accumulate)
  • GemmTransposeRight — C = A·Bᵀ; Span and array overloads (parallel for large row counts)
⚠️ **GitHub.com Fallback** ⚠️