Repository navigation
Module_LinearAlgebra
Location: Home / Linear algebra
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
- 🔖 Vorcyc.Mathematics.LinearAlgebra.LinearEquationSolver class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.MatrixFp32 class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.MatrixFp32<T> class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.MatrixHelper class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.MatrixOperations class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.Quaternion<T> struct
- 🔖 Vorcyc.Mathematics.LinearAlgebra.TensorFp32 class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.TensorFp32<T> class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.VectorSpan class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.MatrixDecomposition class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.MatrixDiagnostics class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.Tensor4D<T> class
- 🔖 Vorcyc.Mathematics.LinearAlgebra.TensorOps class
BasisTransformation is a static class for basis transformations.
-
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。
-
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));
}
}LinearEquationSolver is a static class for solving linear systems.
-
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; optionalaugmentedWorkspace(n×(n+1)) avoids reallocating the augmented matrix.
- Solves Ax = b in place into
-
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。
-
-
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。
-
-
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。
-
-
public static T[] CholeskySolve<T>(Matrix<T> A, T[] b)— symmetric positive definite Ax = b (A = LLᵀ)
-
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
-
SolveLeastSquaresSvd<T>(Matrix<T> designMatrix, ReadOnlySpan<T> y, T? tolerance = null)— thin SVD pseudoinverse for rank-deficient design matrices
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));
}
}MatrixFp32 represents a 2D matrix with basic operations.
-
public int Rows { get; }- Gets row count.
-
public int Columns { get; }- Gets column count.
-
public MatrixFp32(int rows, int columns)- Constructs matrix with given rows and columns.
- Parameters:
-
rows: Row count. -
columns: Column count.
-
-
public MatrixFp32(int size)- Constructs square matrix of given size.
- Parameters:
-
size: MatrixFp32 size (rows and columns).
-
-
public MatrixFp32(float[,] initialValues)- Constructs matrix from 2D array.
- Parameters:
-
initialValues: Initial values as 2D array.
-
-
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.
-
public static implicit operator float[,](MatrixFp32 matrix)- Implicitly converts matrix to 2D array.
- Parameters:
-
matrix: MatrixFp32 to convert.
-
-
public static implicit operator float[][](MatrixFp32 matrix)- Implicitly converts matrix to jagged array.
- Parameters:
-
matrix: MatrixFp32 to convert.
-
-
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.
-
-
public static MatrixFp32 operator +(MatrixFp32 a, MatrixFp32 b)- MatrixFp32 addition operator.
- Parameters:
-
a: First matrix. -
b: Second matrix.
-
- Returns: Sum of two matrices.
-
public static MatrixFp32 operator -(MatrixFp32 a, MatrixFp32 b)- MatrixFp32 subtraction operator.
- Parameters:
-
a: First matrix. -
b: Second matrix.
-
- Returns: Difference of two matrices.
-
public static MatrixFp32 operator *(MatrixFp32 a, MatrixFp32 b)- MatrixFp32 multiplication operator.
- Parameters:
-
a: First matrix. -
b: Second matrix.
-
- Returns: Product of two matrices.
-
public static MatrixFp32 operator *(MatrixFp32 matrix, float scalar)- MatrixFp32–scalar multiplication operator.
- Parameters:
-
matrix: MatrixFp32. -
scalar: Scalar.
-
- Returns: MatrixFp32 times scalar.
-
public static MatrixFp32 operator /(MatrixFp32 matrix, float scalar)- MatrixFp32–scalar division operator.
- Parameters:
-
matrix: MatrixFp32. -
scalar: Scalar.
-
- Returns: MatrixFp32 divided by scalar.
-
public Span<float> GetRow(int rowIndex)- Gets elements of the specified row.
- Parameters:
-
rowIndex: Row index.
-
- Returns:
Spanof row elements.
-
public ReadOnlySpan<float> GetColumn(int columnIndex)- Gets elements of the specified column.
- Parameters:
-
columnIndex: Column index.
-
- Returns:
ReadOnlySpanof column elements.
-
public MatrixFp32 Transpose()- Transposes the matrix.
- Returns: Transposed matrix.
-
public float Determinant()- Computes the matrix determinant.
- Returns: Determinant.
-
public MatrixFp32 Inverse()- Computes the matrix inverse.
- Returns: Inverse matrix.
-
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.
-
-
public void QRDecomposition(out MatrixFp32 Q, out MatrixFp32 R)- QR decomposition.
- Parameters:
-
Q: Output orthogonal matrix. -
R: Output upper triangular matrix.
-
-
public MatrixFp32 CholeskyDecomposition()- Cholesky decomposition.
- Returns: Lower triangular matrix.
-
public static MatrixFp32 Eye(int size)- Creates an identity matrix.
- Parameters:
-
size: MatrixFp32 size (rows and columns).
-
- Returns: Identity matrix.
-
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。
-
-
public void FillRandom()- Fills matrix with random values.
-
public MatrixFp32 Clone()- Creates a deep copy.
- Returns: Deep copy.
-
public override string ToString()- Returns string representation of matrix.
- Returns: String representation.
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);
}
}Matrix<T> is a generic 2D matrix with basic operations.
-
public int Rows { get; }- Gets row count.
-
public int Columns { get; }- Gets column count.
-
public MatrixFp32(int rows, int columns)- Constructs matrix with given rows and columns.
- Parameters:
-
rows: Row count. -
columns: Column count.
-
-
public MatrixFp32(int size)- Constructs square matrix of given size.
- Parameters:
-
size: MatrixFp32 size (rows and columns).
-
-
public MatrixFp32(T[,] initialValues)- Constructs matrix from 2D array.
- Parameters:
-
initialValues: Initial values as 2D array.
-
-
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.
-
public static implicit operator T[,](Matrix<T> matrix)- Implicitly converts matrix to 2D array.
- Parameters:
-
matrix: MatrixFp32 to convert.
-
-
public static implicit operator T[][](Matrix<T> matrix)- Implicitly converts matrix to jagged array.
- Parameters:
-
matrix: MatrixFp32 to convert.
-
-
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.
-
-
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.
-
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.
-
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.
-
public static Matrix<T> operator *(Matrix<T> matrix, T scalar)- MatrixFp32–scalar multiplication operator.
- Parameters:
-
matrix: MatrixFp32. -
scalar: Scalar.
-
- Returns: MatrixFp32 times scalar.
-
public static Matrix<T> operator /(Matrix<T> matrix, T scalar)- MatrixFp32–scalar division operator.
- Parameters:
-
matrix: MatrixFp32. -
scalar: Scalar.
-
- Returns: MatrixFp32 divided by scalar.
-
public Span<T> GetRow(int rowIndex)- Gets elements of the specified row.
- Parameters:
-
rowIndex: Row index.
-
- Returns:
Spanof row elements.
-
public T[] GetColumn(int columnIndex)- Gets elements of the specified column.
- Parameters:
-
columnIndex: Column index.
-
- Returns:
T[]of column elements.
-
public Matrix<T> Transpose()- Transposes the matrix.
- Returns: Transposed matrix.
-
public T Determinant()- Computes the matrix determinant.
- Returns: Determinant.
-
public Matrix<T> Inverse()- Computes the matrix inverse.
- Returns: Inverse matrix.
-
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.
-
-
public void QRDecomposition(out Matrix<T> Q, out Matrix<T> R)- QR decomposition.
- Parameters:
-
Q: Output orthogonal matrix. -
R: Output upper triangular matrix.
-
-
public Matrix<T> CholeskyDecomposition()- Cholesky decomposition.
- Returns: Lower triangular matrix.
-
public static Matrix<T> Eye(int size)- Creates an identity matrix.
- Parameters:
-
size: MatrixFp32 size (rows and columns).
-
- Returns: Identity matrix.
-
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。
-
-
public void FillRandom()- Fills matrix with random values.
-
public Matrix<T> Clone()- Creates a deep copy.
- Returns: Deep copy.
-
public override string ToString()- Returns string representation of matrix.
- Returns: String representation.
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 is a static helper for matrix and array operations。
-
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.
-
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.
-
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.
-
public static bool IsJagged(this Array array)- Determines whether array is jagged.
- Parameters:
-
array: Array。
-
- Returns:
trueif jagged array.
-
public static bool IsMatrix(this Array array)- Determines whether array is multidimensional.
- Parameters:
-
array: Array。
-
- Returns:
trueif multidimensional array.
-
public static bool IsVector(this Array array)- Determines whether array is a vector.
- Parameters:
-
array: Array。
-
- Returns:
trueif vector.
-
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.
-
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.
-
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.
-
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.
-
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.
-
public static int Columns<T>(this T[,] matrix)- Gets column count.
- Parameters:
-
matrix: MatrixFp32.
-
- Returns: Column 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.
-
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.
-
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.
-
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.
-
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.
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 is a static class of matrix operations。
-
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。
-
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> is a generic quaternion struct with basic operations。
-
public T W { get; }- Gets quaternion W component.
-
public T X { get; }- Gets quaternion X component.
-
public T Y { get; }- Gets quaternion Y component.
-
public T Z { get; }- Gets quaternion Z component.
-
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。
-
-
public Quaternion<T> Conjugate()- Returns quaternion conjugate.
- Returns: Quaternion conjugate.
-
public T Norm()- Returns quaternion norm.
- Returns: Quaternion norm.
-
public Quaternion<T> Normalize()- Returns normalized quaternion.
- Returns: Normalized quaternion.
-
public Quaternion<T> Inverse()- Returns quaternion inverse.
- Returns: Quaternion inverse.
-
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.
-
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.
-
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.
-
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.
-
public static bool operator ==(Quaternion<T> left, Quaternion<T> right)- Equality operator for two quaternions.
- Parameters:
-
left: First quaternion。 -
right: Second quaternion。
-
- Returns:
trueif quaternions are equal.
-
public static bool operator !=(Quaternion<T> left, Quaternion<T> right)- Inequality operator for two quaternions.
- Parameters:
-
left: First quaternion。 -
right: Second quaternion。
-
- Returns:
trueif quaternions are not equal.
-
public override string ToString()- Returns string representation.
- Returns: String representation.
-
public override bool Equals(object? obj)- Determines whether object equals this quaternion.
- Parameters:
-
obj: Object to compare with this quaternion。
-
- Returns:
trueif object equals this quaternion.
-
public override int GetHashCode()- Returns hash code.
- Returns: Hash code.
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 is a 3D tensor with basic operations。
-
public float[] Values { get; }- Gets tensor values.
-
public int Width { get; }- Gets tensor width.
-
public int Height { get; }- Gets tensor height.
-
public int Depth { get; }- Gets tensor depth.
-
public TensorFp32(int w, int h, int d)- Initializes tensor with given size.
- Parameters:
-
w: Width。 -
h: Height。 -
d: Depth。
-
-
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。
-
-
public TensorFp32(float[,,] array)- Initializes tensor from 3D array.
- Parameters:
-
array: 3D array used to initialize the tensor。
-
-
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.
-
public void Fill(float value)- Fills tensor with value.
- Parameters:
-
value: Value to fill the tensor with。
-
-
public void Add(TensorFp32 other)- Adds another tensor to this tensor.
- Parameters:
-
other: TensorFp32 to add。
-
-
public void Subtract(TensorFp32 other)- Subtracts another tensor from this tensor.
- Parameters:
-
other: TensorFp32 to subtract。
-
-
public void Multiply(float scalar)- Multiplies this tensor by a scalar.
- Parameters:
-
scalar: Scalar multiplier。
-
-
public TensorFp32 Transpose(int axis1, int axis2)- Transposes tensor along axes.
- Parameters:
-
axis1: First axis。 -
axis2: Second axis。
-
- Returns: New transposed tensor.
-
public float Sum()- Computes the sum of all tensor elements.
- Returns: Sum of all tensor elements.
-
public float Dot(TensorFp32 other)- Computes the dot product of two tensors.
- Parameters:
-
other: Other tensor。
-
- Returns: Dot product of two tensors.
-
public void Normalize()- normalizationTensor。
-
public float Norm()- Computes the tensor norm.
- Returns: TensorFp32 norm.
-
public TensorFp32 Slice(int axis, int index)- Slices tensor along axis.
- Parameters:
-
axis: Axis to slice along。 -
index: Slice index。
-
- Returns: Sliced tensor.
-
public TensorFp32 Clone()- Clones tensor.
- Returns: A new tensor copy.
-
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.
-
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.
-
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.
-
public static bool operator ==(TensorFp32 a, TensorFp32 b)- Equality operator for two tensors.
- Parameters:
-
a: First tensor。 -
b: Second tensor。
-
- Returns:
trueif tensors are equal.
-
public static bool operator !=(TensorFp32 a, TensorFp32 b)- Inequality operator for two tensors.
- Parameters:
-
a: First tensor。 -
b: Second tensor。
-
- Returns:
trueif tensors are not equal.
-
public override string ToString()- Returns string representation of tensor.
- Returns: String representation.
-
public override bool Equals(object? obj)- Determines whether object equals this tensor.
- Parameters:
-
obj: Object to compare with this tensor。
-
- Returns:
trueif object equals this tensor.
-
public override int GetHashCode()- Returns hash code.
- Returns: Hash code.
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> is a generic 3D tensor with basic operations。
-
public Span<T> Values { get; }- Gets tensor values.
-
public int Width { get; }- Gets tensor width.
-
public int Height { get; }- Gets tensor height.
-
public int Depth { get; }- Gets tensor depth.
-
public TensorFp32(int w, int h, int d)- Initializes tensor with given size.
- Parameters:
-
w: Width。 -
h: Height。 -
d: Depth。
-
-
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。
-
-
public TensorFp32(T[,,] array)- Initializes tensor from 3D array.
- Parameters:
-
array: 3D array used to initialize the tensor。
-
-
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.
-
public void Fill(T value)- Fills tensor with value.
- Parameters:
-
value: Value to fill the tensor with。
-
-
public void Add(Tensor<T> other)- Adds another tensor to this tensor.
- Parameters:
-
other: TensorFp32 to add。
-
-
public void Subtract(Tensor<T> other)- Subtracts another tensor from this tensor.
- Parameters:
-
other: TensorFp32 to subtract。
-
-
public void Multiply(T scalar)- Multiplies this tensor by a scalar.
- Parameters:
-
scalar: Scalar multiplier。
-
-
public Tensor<T> Transpose(int axis1, int axis2)- Transposes tensor along axes.
- Parameters:
-
axis1: First axis。 -
axis2: Second axis。
-
- Returns: New transposed tensor.
-
public T Sum()- Computes the sum of all tensor elements.
- Returns: Sum of all tensor elements.
-
public T Dot(Tensor<T> other)- Computes the dot product of two tensors.
- Parameters:
-
other: Other tensor。
-
- Returns: Dot product of two tensors.
-
public void Normalize()- normalizationTensor。
-
public T Norm()- Computes the tensor norm.
- Returns: TensorFp32 norm.
-
public Tensor<T> Slice(int axis, int index)- Slices tensor along axis.
- Parameters:
-
axis: Axis to slice along。 -
index: Slice index。
-
- Returns: Sliced tensor.
-
public Tensor<T> Clone()- Clones tensor.
- Returns: A new tensor copy.
-
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.
-
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.
-
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.
-
public static bool operator ==(Tensor<T> a, Tensor<T> b)- Equality operator for two tensors.
- Parameters:
-
a: First tensor。 -
b: Second tensor。
-
- Returns:
trueif tensors are equal.
-
public static bool operator !=(Tensor<T> a, Tensor<T> b)- Inequality operator for two tensors.
- Parameters:
-
a: First tensor。 -
b: Second tensor。
-
- Returns:
trueif tensors are not equal.
-
public override string ToString()- Returns string representation of tensor.
- Returns: String representation.
-
public override bool Equals(object? obj)- Determines whether object equals this tensor.
- Parameters:
-
obj: Object to compare with this tensor。
-
- Returns:
trueif object equals this tensor.
-
public override int GetHashCode()- Returns hash code.
- Returns: Hash code.
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);
}
}VectorSpan is a static utility. Math vectors use ReadOnlySpan<T>, Span<T>, or T[], avoiding confusion with BCL System.Numerics.Vector<T> (SIMD registers).
-
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).
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);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
-
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 honorComputingContext; 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ᵀ
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 });MatrixFp32 numerical diagnostics utilities.
-
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.
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.
-
Tensor4DShape— shape andElementCount - Indexer
[d0, d1, d2, d3]andGetLinearIndex -
Filland other batch operations
NHWC tensor layout utilities reused by convolution im2col paths.
-
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ᵀ;Spanand array overloads (parallel for large row counts)
-
- 🔖 ArrayExtension class
- 🔖 BaseConverter class
- 🔖 BitMathExtension class
- 🔖 Combinatorics class
- 🔖 ConstantsFp32 class
- 🔖 NumberMapper class
- 🔖 PinnableArray<T> class
- 🔖 SimpleRNG_Fp32 and SimpleRNG_Fp64 classes
- 🔖 TrigonometryHelper class
- 🔖 VMath class
- 🔖 Pinned buffers (Buffers)
- 🔖 IPinnedBuffer<T> interface
- 🔖 POHBuffer<T> class
- 🔖 NativeBuffer<T> class
-
- 🔖 0.9 classifier walkthrough
- 🔖 KNN<T> class
- 🔖 MultipleLinearRegression<T> class
- 🔖 SimpleLinearRegression<T> class
- 🔖 SupportVectorMachine<TSelf> class
- 🔖 DBSCAN<T> class
- 🔖 ExpectationMaximization<T> class
- 🔖 GMM<T> class
- 🔖 HierarchicalClustering<T> class
- 🔖 KMeansClusterer<T> class
- 🔖 VectorQuantization<T> class
- 🔖 FactorAnalysis<T> class
- 🔖 PCA<TSelf> class
- 🔖 TSNE<T> class
- 🔖 Distance metric classes
-
📒 Examples
-
📒 GPU 策略说明
- 🔖 为何放弃主包 GPU
- 🔖 当前性能路径
- 🔖 若仍需要更强算力
-
📒 计算上下文模块
-
📒 核心模块
-
📒 深度学习模块
-
📒 线性代数模块
-
📒 机器学习模块
- 🔖 0.9 分类器完整示例
- 🔖 KNN<T> 类
- 🔖 MultipleLinearRegression<T> 类
- 🔖 SimpleLinearRegression<T> 类
- 🔖 SupportVectorMachine<TSelf> 类
- 🔖 DBSCAN<T> 类
- 🔖 ExpectationMaximization<T> 类
- 🔖 GMM<T> 类
- 🔖 HierarchicalClustering<T> 类
- 🔖 KMeansClusterer<T> 类
- 🔖 VectorQuantization<T> 类
- 🔖 FactorAnalysis<T> 类
- 🔖 PCA<TSelf> 类
- 🔖 TSNE<T> 类
- 🔖 距离度量类
-
📒 信号处理模块
-
📒 数值模块
-
📒 统计模块
- 🔖 基础统计函数
- 🔖 高级统计函数
- 🔖 稳健统计 / RunningMoments
- 🔖 其它统计函数
- 🔖 分布相关函数
- 🔖 时间序列分析
- 🔖 IComparable 扩展
- 🔖 ExtremeValueFinder
- 🔖 INumber 扩展
-
📒 FFTW 扩展
-
📒 示例