package main
import (
"fmt"
"math"
)
func main() {
// 行列のデータ
matrix := [][]float64{
{2.5, 3.7, 4.8, 1.2},
{1.0, 2.0, 3.0, 4.0},
{0.5, 1.5, 2.5, 3.5},
}
numRows := len(matrix)
numCols := len(matrix[0])
// 各列の平均を計算
averages := make([]float64, numCols)
for j := 0; j < numCols; j++ {
sum := 0.0
for i := 0; i < numRows; i++ {
sum += matrix[i][j]
}
averages[j] = sum / float64(numRows)
}
// 各列の各データと平均の差の二乗和を計算
sumOfSquaredDiffs := make([]float64, numCols)
for j := 0; j < numCols; j++ {
for i := 0; i < numRows; i++ {
diff := matrix[i][j] - averages[j]
sumOfSquaredDiffs[j] += diff * diff
}
}
// 各列の分散を計算
variances := make([]float64, numCols)
for j := 0; j < numCols; j++ {
variances[j] = sumOfSquaredDiffs[j] / float64(numRows)
}
// 各列の標準偏差を計算
stdDevs := make([]float64, numCols)
for j := 0; j < numCols; j++ {
stdDevs[j] = math.Sqrt(variances[j])
}
// 行列の各要素を標準偏差で正規化
normalizedMatrix := make([][]float64, numRows)
for i := 0; i < numRows; i++ {
normalizedMatrix[i] = make([]float64, numCols)
for j := 0; j < numCols; j++ {
normalizedMatrix[i][j] = (matrix[i][j] - averages[j]) / stdDevs[j]
}
}
// 正規化された行列を表示
fmt.Println("正規化された行列:")
for i := 0; i < numRows; i++ {
fmt.Println(normalizedMatrix[i])
}
}