Fitting multiple data sets to single curve in least square sense

1 ビュー (過去 30 日間)
Abdulllah
Abdulllah 2022 年 3 月 11 日
コメント済み: AndresVar 2022 年 3 月 11 日
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
x2=(0:1:10)'+1;
x3=(0:1:10)'+2;
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
figure
plot(x,y,'*',x,f(F_fitted,x),'g');
legend('data','fit')
The actuall dataset is attached.

回答 (2 件)

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2022 年 3 月 11 日
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.
x1=(0:1:10)';
x2=(0:1:10)'+1;
x3=(0:1:10)'+2;
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]);
end
for i=1:size(x,2)
subplot(1,3,i)
plot(x(:,i),y(:,i),'*',x(:,i),model(F_fitted(i,:),x(:,i)),'g')
title(['(X_' num2str(i) ',Y_' num2str(i) ')'])
end
  9 件のコメント
AndresVar
AndresVar 2022 年 3 月 11 日
@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 - (mathworks.com)

サインインしてコメントする。


AndresVar
AndresVar 2022 年 3 月 11 日
編集済み: AndresVar 2022 年 3 月 11 日
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 ";"
x=[x1;x2;x3]
Then you should probably sort it and apply same sorting to y Sort array elements - MATLAB sort (mathworks.com)
  1 件のコメント
Abdulllah
Abdulllah 2022 年 3 月 11 日
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.

サインインしてコメントする。

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by