I need to fit two x,y data sets to two different functions that share the same parameters. Is there a simple way to do this?
Show older comments
I have one data set that reprents the population of one species as a function if x, and the other that represents the population another species as a function of x. These populations depend on the same paramters. When one d creases the other increases. So I have two functions, but the same parameters. I want to fit these two data sets simultaneously for the 5 parameters. I figu ed out how to fit two datasets to the same function with different parameters, but I need to fit two dTa sets to different functions with the same parameters and I cannot figure it out. Thanks for any insight. Cathy
Answers (1)
Star Strider
on 17 Nov 2016
If you write your functions correctly, this will work. (I tested it with arbitrary data and functions. It works.)
The Code —
x_mtx = [x1(:) x2(:)]; % Concatenate Vectors To Create ‘x_mtx’
y_mtx = [y1(:) y2(:)]; % Concatenate Vectors To Create ‘y_mtx’
fun1 = @(x,xdata) ...; % Objective Function #1
fun2 = @(x,xdata) ...; % Objective Function #2
fun = @(x,xdata) [fun1(x,xdata(:,1)), fun2(x,xdata(:,2))]; % Composite Function
x0 = rand(5,1); % Initial Parameter Estimates
X = lsqcurvefit(fun, x0, x_mtx, y_mtx); % Estimate Parameters
Obviously, your different ‘x’ and ‘y’ data vectors all have to have the same lengths, or you will not be able to create the ‘x_mtx’ and ‘y_mtx’ arrays, and so will not be able to estimate your parameters.
4 Comments
Catherine Royer
on 17 Nov 2016
Edited: Star Strider
on 17 Nov 2016
Star Strider
on 17 Nov 2016
My pleasure.
The ‘xdata’ value becomes defined as ‘x_mtx’ when lsqcurvefit calls ‘fun’ and passes ‘x_mtx’ to it.
Parameter estimation and other optimisation problems are sensitive to the initial parameter estimates. If you have the Global Optimization Toolbox, consider using the patternsearch or GlobalSearch functions to get better initial estimates. Your functions have products of exponential functions that may be difficult to estimate successfully.
You refer to ‘x-axis’. If you are trying to plot it, you need to plot:
figure(1)
plot(x_mtx(:,1), y_mtx(:,1), fun1(x,x_mtx(:,1))
hold on
plot(x_mtx(:,2), y_mtx(:,2), fun2(x,x_mtx(:,2))
hold off
grid
That is how I have referred to them and defined them in ‘fun’.
Changjiang
on 19 Nov 2023
Hi Star,
Why I got the error:
"Error using lsqcurvefit
Function value and YDATA sizes are not equal."
I just copied the code you wrote.
Best
CJ
Star Strider
on 19 Nov 2023
I have no idea in your specific instance.
This can occur if the objective function returns matrices that are transposes of the data, so check that.
Categories
Find more on Get Started with Curve Fitting Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!