I want to use ceres::DynamicAutoDiffCostFunction to calculate the minimum value of the function y=a[0]+a[1]x+a[2]x^2+a[3]x^3, where x=b[0]x_0 +b[1]x_1+b[2]x_2+...+b[n]x_n, the specific number of x is determined by the length of the b coefficient array

I've been trying for a long time but always get an error using DynamicAutoDiffCostFunction

struct CostFunction {
    CostFunction(std::vector<double>& a, std::vector<double>& b, int num_x): a_(a), b_(b), num_params(num_x) {}

    template <typename T>
    bool CostFunction::operator()(const T* const* parameters, T* residual) const {
        T z_est = T(0.0);

        T x_sum = T(0.0);
        for(int i = 0; i < num_params; ++i) {
            x_sum += b[j] * parameters[0][j];
        }
        z_est += a[0] + a[1] * x_sum + a[2] * ceres::pow(x_sum, 2) + a[3] * ceres::pow(x_sum, 3)

        residual[0] = z_est;
        return true;
    }

private:
    std::vector<double> a_;
    std::vector<double> b_;
    int num_params;
};

void Solver(std::vector<double>& a, std::vector<double>& b, const int num_params) {
    std::vector<double> x(num_params, 0.5);
    ceres::Problem* problem = new ceres::Problem;
    CostFunction* cost_function = new CostFunction(a, b, num_params);

    for(int i = 0; i < num_params; ++i) {
        problem->AddParameterBlock(&x[i], 1);
        problem->SetParameterLowerBound(&x[i], 0, 0.0);
        problem->SetParameterUpperBound(&x[i], 0, 1.0);
    }

    ceres::DynamicAutoDiffCostFunction<CostFunction, 1> dynamic_cost_function(cost_function);
    dynamic_cost_function.AddParameterBlock(num_params);
    dynamic_cost_function.SetNumResiduals(1);
    problem->AddResidualBlock(&dynamic_cost_function, nullptr, x.data());

    ceres::Solver::Options options;
    options.minimizer_progress_to_stdout = true;
    ceres::Solver::Summary summary;
    ceres::Solve(options, problem, &summary);

    // std::cout << summary.FullReport() << std::endl;
    for(int i = 0; i < num_params; ++i) {
        std::cout << "x[" << i << "] = " << x[i] << std::endl;
    }
}
0

There are 0 answers