【发布时间】:2026-01-08 14:10:01
【问题描述】:
如何对矩阵进行归一化?
假设我有一个 2x3 矩阵:
1 2 3
4 5 6
归一化矩阵为:1/sqrt(pow(2,2) + pow(3,2)) 2/sqrt(pow(2,2) + pow(3,2)) 3/sqrt(pow(2,2) + pow(3,2))
4/sqrt(pow(5,2) + pow(6,2)) 5/sqrt(pow(5,2) + pow(6,2)) 6/sqrt(pow(5,2) + pow(6,2))
这是我的示例代码:
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main(){
int rows, cols, rowCounter, colCounter, r, c;
int initial[100], inputMatrix[100][100], rowSum[100] = {0}, norm[100][100], square[100] = {0};
printf("Enter size of a matrix\n");
scanf("%d %d", &rows, &cols);
printf("Enter matrix of size %dX%d\n", rows, cols);
/* Input matrix */
for(rowCounter = 0; rowCounter < rows; rowCounter++){
for(colCounter = 0; colCounter < cols; colCounter++){
scanf("%d", &inputMatrix[rowCounter][colCounter]);
}
}
for(r = 0; r < rows; r++)
{
for(c = 1; c < cols; c++)
{
float a;
a == inputMatrix[r][c];
square[r] += pow(a, 2);
}
printf("%.2lf ", square[r]);
}
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
norm[rowCounter][colCounter] == (inputMatrix[rowCounter][colCounter]) / sqrt(square[rowCounter]);
}
}
printf("\nNormalized Matrix:\n");
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
printf("%.3lf ", norm[rowCounter][colCounter]);
}
printf("\n");
}
getch();
return 0;
}
【问题讨论】:
-
我不知道我的代码出了什么问题,它给我的平方是 0.000 0.000,标准都是 0.000
-
您知道您的许多声明是
int而不是double或float,对吗?因此,例如,如果您通过square[r],使用%lf格式的printf肯定会失败,因为它将作为int传递。将您的声明修正为double。 -
更糟糕的是,您的
norm矩阵是int。这意味着任何小数部分都将被丢弃。摆脱矩阵值的所有int声明。 -
另外,在此处发布代码之前,打开编译器警告并修复它们。现代 C 编译器应该警告传递给
printf的数据类型不正确。