龙空技术网

用c语言实现matlab polyfit函数

酒足饭饱抡大锤 150

前言:

目前大家对“matlab转c语言”可能比较关注,小伙伴们都想要了解一些“matlab转c语言”的相关资讯。那么小编在网络上收集了一些对于“matlab转c语言””的相关知识,希望你们能喜欢,同学们一起来了解一下吧!

#include <stdio.h>#include <math.h>void polyfit(double* x, double* y, int degree, double* coeffs) {    int i, j, k;    int n = degree + 1;    double X[2 * n];    for (i = 0; i < 2 * n; i++) {        X[i] = 0;        for (j = 0; j < n; j++)            X[i] += pow(x[j], i);    }    double B[n][n + 1], a[n];    for (i = 0; i < n; i++)        for (j = 0; j < n; j++)            B[i][j] = X[i + j];    double Y[n];    for (i = 0; i < n; i++) {        Y[i] = 0;        for (j = 0; j < n; j++)            Y[i] += pow(x[j], i) * y[j];    }    for (i = 0; i < n; i++)        B[i][n] = Y[i];    n--;    for (i = 0; i < n; i++) {        for (k = i + 1; k < n; k++) {            double t = B[k][i] / B[i][i];            for (j = 0; j <= n; j++)                B[k][j] -= t * B[i][j];        }    }    for (i = n - 1; i >= 0; i--) {        a[i] = B[i][n];        for (j = 0; j < n; j++)            if (j != i)                a[i] -= B[i][j] * a[j];        a[i] /= B[i][i];    }    for (i = 0; i < degree + 1; i++)        coeffs[i] = a[i];}int main() {    double x[] = {1, 2, 3, 4};    double y[] = {1, 4, 9, 16};    int degree = 2;    double coeffs[100];    polyfit(x, y, degree, coeffs);    int i;    for (i = 0; i < degree + 1; i++)        printf("%lf ", coeffs[i]);    return 0;}

该代码使用数组“x”和“y”作为输入,其中“degree”是多项式的次数。它返回多项式的系数,存储在数组“coeffs”中。

标签: #matlab转c语言 #matlab语言转c语言