gitee.com/quant1x/num@v0.3.2/matrix.go (about)

     1  package num
     2  
     3  // Concat1D
     4  //
     5  //	Translates slice objects to concatenation along the second axis.
     6  //	沿第二个轴将切片对象转换为串联
     7  func Concat1D[T Number](a, b, c []T) [][]T {
     8  	length := len(a)
     9  	cLen := 3 // a,b,c TODO:这个位置需要扩展, 如果传入的是2或者3个以上的数组怎么处理?
    10  	rows := make([][]T, length)
    11  	for i := 0; i < length; i++ {
    12  		col := make([]T, cLen)
    13  		col[0] = a[i]
    14  		col[1] = b[i]
    15  		col[2] = c[i]
    16  		rows[i] = col
    17  	}
    18  	return rows
    19  }
    20  
    21  // Transpose2D 矩阵转置
    22  func Transpose2D[T Number](x [][]T) [][]T {
    23  	length := len(x[0])
    24  	cLen := len(x)
    25  	rows := make([][]T, length)
    26  	for i := 0; i < length; i++ {
    27  		col := make([]T, cLen)
    28  		for j := 0; j < cLen; j++ {
    29  			col[j] = x[j][i]
    30  		}
    31  		rows[i] = col
    32  	}
    33  	return rows
    34  }
    35  
    36  // Inverse 计算矩阵的(乘法)逆
    37  //
    38  //	Compute the (multiplicative) inverse of a matrix.
    39  //
    40  //	Given a square matrix `a`, return the matrix `ainv` satisfying
    41  //	``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.
    42  func Inverse(a [][]float64) [][]float64 {
    43  	var n = len(a)
    44  
    45  	// Create augmented matrix
    46  	var augmented = make([][]float64, n)
    47  	for i := range augmented {
    48  		augmented[i] = make([]float64, 2*n)
    49  		for j := 0; j < n; j++ {
    50  			augmented[i][j] = a[i][j]
    51  		}
    52  	}
    53  	for i := 0; i < n; i++ {
    54  		augmented[i][i+n] = 1
    55  	}
    56  
    57  	// Perform Gaussian elimination
    58  	for i := 0; i < n; i++ {
    59  		var pivot = augmented[i][i]
    60  		for j := i + 1; j < n; j++ {
    61  			var factor = augmented[j][i] / pivot
    62  			for k := i; k < 2*n; k++ {
    63  				augmented[j][k] -= factor * augmented[i][k]
    64  			}
    65  		}
    66  	}
    67  
    68  	// Perform back-substitution
    69  	for i := n - 1; i >= 0; i-- {
    70  		var pivot = augmented[i][i]
    71  		for j := i - 1; j >= 0; j-- {
    72  			var factor = augmented[j][i] / pivot
    73  			for k := i; k < 2*n; k++ {
    74  				augmented[j][k] -= factor * augmented[i][k]
    75  			}
    76  		}
    77  	}
    78  
    79  	// Normalize rows
    80  	for i := 0; i < n; i++ {
    81  		var pivot = augmented[i][i]
    82  		for j := 0; j < 2*n; j++ {
    83  			augmented[i][j] /= pivot
    84  		}
    85  	}
    86  
    87  	// Extract inverse from augmented matrix
    88  	var inverse = make([][]float64, n)
    89  	for i := range inverse {
    90  		inverse[i] = make([]float64, n)
    91  	}
    92  	for i := 0; i < n; i++ {
    93  		for j := 0; j < n; j++ {
    94  			inverse[i][j] = augmented[i][j+n]
    95  		}
    96  	}
    97  
    98  	return inverse
    99  }