1 Star 4 Fork 11

王布衣 / pandas

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
matrix.go 2.15 KB
一键复制 编辑 原始数据 按行查看 历史
王布衣 提交于 2023-02-25 01:57 . !74#I6HES3实现numpy.dot函数
package stat
// Concat1D
//
// Translates slice objects to concatenation along the second axis.
// 沿第二个轴将切片对象转换为串联
func Concat1D[T Number](a, b, c []T) [][]T {
length := len(a)
cLen := 3 // a,b,c TODO:这个位置需要扩展, 如果传入的是2或者3个以上的数组怎么处理?
rows := make([][]T, length)
for i := 0; i < length; i++ {
col := make([]T, cLen)
col[0] = a[i]
col[1] = b[i]
col[2] = c[i]
rows[i] = col
}
return rows
}
// Transpose2D 矩阵转置
func Transpose2D[T Number](x [][]T) [][]T {
length := len(x[0])
cLen := len(x)
rows := make([][]T, length)
for i := 0; i < length; i++ {
col := make([]T, cLen)
for j := 0; j < cLen; j++ {
col[j] = x[j][i]
}
rows[i] = col
}
return rows
}
// Inverse 计算矩阵的(乘法)逆
//
// Compute the (multiplicative) inverse of a matrix.
//
// Given a square matrix `a`, return the matrix `ainv` satisfying
// ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.
func Inverse(a [][]float64) [][]float64 {
var n = len(a)
// Create augmented matrix
var augmented = make([][]float64, n)
for i := range augmented {
augmented[i] = make([]float64, 2*n)
for j := 0; j < n; j++ {
augmented[i][j] = a[i][j]
}
}
for i := 0; i < n; i++ {
augmented[i][i+n] = 1
}
// Perform Gaussian elimination
for i := 0; i < n; i++ {
var pivot = augmented[i][i]
for j := i + 1; j < n; j++ {
var factor = augmented[j][i] / pivot
for k := i; k < 2*n; k++ {
augmented[j][k] -= factor * augmented[i][k]
}
}
}
// Perform back-substitution
for i := n - 1; i >= 0; i-- {
var pivot = augmented[i][i]
for j := i - 1; j >= 0; j-- {
var factor = augmented[j][i] / pivot
for k := i; k < 2*n; k++ {
augmented[j][k] -= factor * augmented[i][k]
}
}
}
// Normalize rows
for i := 0; i < n; i++ {
var pivot = augmented[i][i]
for j := 0; j < 2*n; j++ {
augmented[i][j] /= pivot
}
}
// Extract inverse from augmented matrix
var inverse = make([][]float64, n)
for i := range inverse {
inverse[i] = make([]float64, n)
}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
inverse[i][j] = augmented[i][j+n]
}
}
return inverse
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/quant1x/pandas.git
git@gitee.com:quant1x/pandas.git
quant1x
pandas
pandas
v0.9.26

搜索帮助

344bd9b3 5694891 D2dac590 5694891