多元最小二乘拟合C语言代码
时间: 2023-07-10 11:09:15 浏览: 147
以下是使用多元最小二乘法进行拟合的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAXN 1000
#define MAXM 10
// 定义矩阵结构体
typedef struct {
double a[MAXN][MAXM];
int m, n;
} Matrix;
// 矩阵初始化函数
void init_matrix(Matrix *mat, int m, int n) {
mat->m = m;
mat->n = n;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
mat->a[i][j] = 0.0;
}
}
}
// 矩阵加法函数
void add_matrix(Matrix *mat1, Matrix *mat2, Matrix *res) {
int m = mat1->m;
int n = mat1->n;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res->a[i][j] = mat1->a[i][j] + mat2->a[i][j];
}
}
}
// 矩阵乘法函数
void mul_matrix(Matrix *mat1, Matrix *mat2, Matrix *res) {
int m = mat1->m;
int n = mat2->n;
int k = mat1->n;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res->a[i][j] = 0.0;
for (int l = 0; l < k; l++) {
res->a[i][j] += mat1->a[i][l] * mat2->a[l][j];
}
}
}
}
// 矩阵转置函数
void transpose_matrix(Matrix *mat, Matrix *res) {
int m = mat->m;
int n = mat->n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
res->a[i][j] = mat->a[j][i];
}
}
}
// 多元最小二乘拟合函数
void fit_least_squares(int n, int m, double x[][MAXM], double y[], double b[]) {
Matrix A, B, X, Y, AT, ATA, ATB, ATA_inv;
init_matrix(&A, n, m);
init_matrix(&B, n, 1);
init_matrix(&X, m, 1);
init_matrix(&Y, n, 1);
init_matrix(&AT, m, n);
init_matrix(&ATA, m, m);
init_matrix(&ATB, m, 1);
init_matrix(&ATA_inv, m, m);
// 将输入数据赋值给矩阵 A 和 B
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
A.a[i][j] = x[i][j];
}
B.a[i][0] = y[i];
}
// 计算 AT 和 ATA
transpose_matrix(&A, &AT);
mul_matrix(&AT, &A, &ATA);
// 计算 ATB
mul_matrix(&AT, &B, &ATB);
// 计算 ATA_inv
double det = ATA.a[0][0] * ATA.a[1][1] - ATA.a[0][1] * ATA.a[1][0];
ATA_inv.a[0][0] = ATA.a[1][1] / det;
ATA_inv.a[0][1] = -ATA.a[0][1] / det;
ATA_inv.a[1][0] = -ATA.a[1][0] / det;
ATA_inv.a[1][1] = ATA.a[0][0] / det;
// 计算 X
mul_matrix(&ATA_inv, &ATB, &X);
// 将拟合系数赋值给输出数组 b
for (int i = 0; i < m; i++) {
b[i] = X.a[i][0];
}
}
int main() {
int n, m;
double x[MAXN][MAXM], y[MAXN], b[MAXM];
printf("Enter the number of data points: ");
scanf("%d", &n);
printf("Enter the number of independent variables: ");
scanf("%d", &m);
printf("Enter the data points (x, y):\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%lf", &x[i][j]);
}
scanf("%lf", &y[i]);
}
fit_least_squares(n, m, x, y, b);
printf("The fitting coefficients are:\n");
for (int i = 0; i < m; i++) {
printf("b%d = %lf\n", i + 1, b[i]);
}
return 0;
}
```
该示例代码中使用了矩阵结构体来表示矩阵,并实现了矩阵初始化、矩阵加法、矩阵乘法、矩阵转置等基本操作函数。在 `fit_least_squares` 函数中,将输入数据存储到矩阵 A 和 B 中,并依次计算出 AT、ATA、ATB 和 ATA_inv 等矩阵,最终得到拟合系数矩阵 X,并将其转换为输出数组 b 返回。在主函数中,首先读取输入数据,然后调用 `fit_least_squares` 函数进行拟合,最后输出拟合系数。
阅读全文