关于使用lsqnonlin求解向量输入最小二乘问题的报错咨询
lsqnonlin Error in Your Least Squares Problem Hey there, let's break down why you're hitting that error and how to fix it quickly. The core issue here is how you're structuring your objective function for lsqnonlin—it doesn't expect a cell array of separate functions, but a single function that returns a residual vector (where each element is one of the terms you want to include in the sum of squares).
What Went Wrong
Your current code defines f = {f_1, f_2} as a cell array of two function handles. But lsqnonlin requires its first input to be a single function handle that:
- Takes a single parameter vector (in your case, this vector will hold
tandx, e.g.,params = [t, x]) - Returns a column (or row) vector containing the values of
f_1andf_2evaluated at those parameters.
When you pass the cell array, lsqnonlin tries to treat it as a callable function, which leads to the error you're seeing.
The Correct Approach
Let's rewrite your code to fit lsqnonlin's requirements:
% Define a single objective function that returns the residual vector % params is a 2-element vector: params(1) = t, params(2) = x f_obj = @(params) [ sin(params(1) + params(2).^2); % f_1(t,x) cos(params(2).^2) + 3.*params(1).^2 % f_2(t,x) ]; % Initial guess: [t_initial, x_initial] = [1, 2] initial_guess = [1, 2]; % Call lsqnonlin to find the optimal t and x [optimal_params, min_squared_error] = lsqnonlin(f_obj, initial_guess); % Extract and display the results t_opt = optimal_params(1); x_opt = optimal_params(2); fprintf('Optimal t: %.4f\n', t_opt); fprintf('Optimal x: %.4f\n', x_opt); fprintf('Minimum sum of squared errors: %.4f\n', min_squared_error);
Quick Extra Tip
If you need to add constraints (e.g., t must be between 0 and 5, x between -3 and 3), you can add lower and upper bound arguments to lsqnonlin:
lb = [0, -3]; % Lower bounds for t and x ub = [5, 3]; % Upper bounds for t and x [optimal_params, min_squared_error] = lsqnonlin(f_obj, initial_guess, lb, ub);
内容的提问来源于stack exchange,提问作者will_cheuk

