CodexBloom - Programming Q&A Platform

MATLAB 'odr' function yields unexpected results with non-linear model fitting in R2023b

👀 Views: 22 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
matlab non-linear odr curve-fitting

I'm reviewing some code and I'm maintaining legacy code that I'm getting frustrated with I've looked through the documentation and I'm still confused about I'm trying to fit a non-linear model to some data using MATLAB's 'odr' function, but I'm getting unexpected results that don't seem to fit my data well... My data consists of two variables, x and y, which I believe follow a power law relationship. Here's the function I am trying to fit: ```matlab function y = power_law(x, a, b) y = a .* x.^b; end ``` I set up my data and initial parameters like this: ```matlab x_data = [1, 2, 3, 4, 5]; y_data = [2, 8, 18, 32, 50]; initial_params = [1, 2]; % Using 'odr' for orthogonal distance regression model = @(params, x) power_law(x, params(1), params(2)); results = odr(model, x_data, y_data, initial_params); ``` However, when I look at the fitted parameters, the output is: ```matlab results.params ``` This returns `[0.5, 1]`, which doesn't match my expectations based on the data. My initial guess was based on visual inspection, and I was hoping for something closer to `[2, 1.5]`. I've tried tweaking the initial parameters and even using different data scaling approaches, but I still can't get a sensible fit. The residuals also seem quite large. Here's how I computed the residuals: ```matlab fitted_y = power_law(x_data, results.params(1), results.params(2)); residuals = y_data - fitted_y; ``` I also checked the data with a simple linear regression to see if it was just my method, but that seems to give reasonable outputs. Am I missing something in my approach with 'odr', or is there a specific detail about using non-linear models in MATLAB that I should be aware of? Any insights would be greatly appreciated! I'm working on a CLI tool that needs to handle this. I'm developing on CentOS with Matlab. Any examples would be super helpful. I appreciate any insights! Thanks for any help you can provide!