Fitting multiple data sets to single curve in least square sense

14 views (last 30 days)
I am trying to fit multiple data sets i.e., x1,x2,x3 -> y1,y2,y3 to a single cuve f following this exapmle. However, it returns error that the second coulmn must be a vector. The ultimate goal is to fit to a curve such that the sum(abs(f(x)-y))<3. How can I do it in matlab starting with the following example
x1=(0:1:10)'; % Explanatory variable
x=[x1 x2 x3];
y = 5 + 3*x + 7*x.^2;
y = y + 2*randn((size(x)));% Add some noise to response variable
% Define function that will be used to fit data
% (F is a vector of fitting parameters)
f = @(F,x) F(1) + F(2).*x + F(3).*x.^2;
F_fitted = nlinfit(x,y,f,[1 1 1]); %Error: Requires a vector second input argument.
% Display fitted coefficients
disp(['F = ',num2str(F_fitted)])
% Plot the data and fit
The actuall dataset is attached.

Answers (2)

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh on 11 Mar 2022
the nlinfit function take a vector as second input y, because it's cost function for optimization and regression is based on scalar output. you should fitt each model separately.
x=[x1 x2 x3];
y = 5 + 3*x + 7*x.^2;
y = y + 2*randn((size(x)));
model = @(F,x) F(1) + F(2).*x + F(3).*x.^2;
for i=1:size(x,2)
F_fitted(i,:) = nlinfit(x(:,i),y(:,i),model,[1 1 1]);
for i=1:size(x,2)
title(['(X_' num2str(i) ',Y_' num2str(i) ')'])
AndresVar on 11 Mar 2022
@Abdulllah like Abolfazi said, your data won't fit a single f(x). The data fits a*exp(b*x) pretty well but for different values of a.
There might be another parameter that is missing that collapses the data.
Find the different coefficient by fitting each series or find them like this: simulataneous Curve fitting - (

Sign in to comment.

AndresVar on 11 Mar 2022
Edited: AndresVar on 11 Mar 2022
x1,x2,x3 are column vectors that you combined into a matrix, so then y was evaluated to a matrix also.
nlinfit expects vectors not matrices
to fix it, combine x1 x2 x3 into 1 long column vector using ";"
Then you should probably sort it and apply same sorting to y Sort array elements - MATLAB sort (
  1 Comment
Abdulllah on 11 Mar 2022
If I combined x1,x2,x3 to a single vector and do the same with y, Matlab finds a very bad solution. I am looking for a better options to get a single optimium function to fit all the datasets.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by