CodexBloom - Programming Q&A Platform

Unexpected behavior when using 'lsqcurvefit' with custom residual function in MATLAB R2023b

👀 Views: 88 đŸ’Ŧ Answers: 1 📅 Created: 2025-09-01
matlab optimization curve-fitting MATLAB

I can't seem to get Quick question that's been bugging me - I'm trying to fit a non-linear model to my data using `lsqcurvefit` in MATLAB R2023b, but I'm encountering unexpected behavior when I define a custom residual function... My goal is to fit a model defined as `y = a * exp(b * x) + c` where `a`, `b`, and `c` are the parameters I want to optimize. I have created a custom residual function that calculates the difference between the observed data and the model predictions, but when I run `lsqcurvefit`, the results do not converge as expected, and I'm getting a warning: `Warning: The algorithm failed to converge.` Here's a simplified version of my code: ```matlab % Sample data x_data = [1, 2, 3, 4, 5]; y_data = [2.7, 6.1, 9.5, 15.5, 22.3]; % Initial parameter guess initial_params = [1, 1, 1]; % Custom residual function function residuals = myResidual(params, x, y) model = params(1) * exp(params(2) * x) + params(3); residuals = y - model; end % Fit model using lsqcurvefit [optimized_params, resnorm] = lsqcurvefit(@(p, x) myResidual(p, x, y_data), initial_params, x_data, y_data); ``` I've checked the dimension of the inputs and outputs, and they seem correct. What could be causing the convergence issue? Are there best practices I should follow when implementing a custom residual function with `lsqcurvefit`? Any insights would be appreciated! For context: I'm using Matlab on Ubuntu. Thanks in advance! Am I missing something obvious? I'm using Matlab stable in this project. Thanks for your help in advance!