How to fit data to a function form
7 views (last 30 days)
Show older comments
Fynn Oppermann
on 19 Jan 2022
Commented: Star Strider
on 19 Jan 2022
Apologies if my use of terminology is wrong.
I essentially have four equal sized data sets (eg. x y z w) and I want find an equation that describes one of those data sets as a funtion of the other three. To begin with I'm assuming this is a linear relationship i.e. x = a*y + b*z + c*w.
Is there a way to fit these data sets to find the values of the coefficients a b c?
Thanks for your help!
0 Comments
Accepted Answer
Star Strider
on 19 Jan 2022
x = randn(10,1);
y = randn(10,1);
z = randn(10,1);
w = randn(10,1);
DM = [y(:) z(:) w(:)]; % Design Matrix
abc = DM \ x(:)
Results = table(x(:),DM*abc,x(:)-DM*abc, 'VariableNames',{'Original x','Regressed x','Difference'})
meanDifference = mean(Results.Difference)
.
2 Comments
Star Strider
on 19 Jan 2022
My pleasure!
It will only work for linear relations, however coding it for nonlilnear relations would be straightforward and may not involve anythng other than core MATLAB. For a nonlinear regression, one approach would be to use fminsearch if other Toolboxes are not available.
Example —
x = randn(10,1);
y = randn(10,1);
z = randn(10,1);
w = randn(10,1);
yzw = [y(:) z(:) w(:)]; % Contatenate Column Vectors
% % % FUNCTION: exp(a*y) * sin(2*pi*b*z) + c*w
objfcn = @(b,iv) exp(b(1)*iv(:,1)) .* sin(2*pi*b(2).*iv(:,2)) + b(3)*iv(:,3)
B = fminsearch(@(b) norm(x(:) - objfcn(b,yzw)), rand(3,1))
fprintf(1, '\n\ta = %9.4f\n\tb = %9.4f\n\tc = %9.4f\n',B)
Results = table(x(:), objfcn(B,yzw), x(:)-objfcn(B,yzw), 'VariableNames',{'Original x','Regressed x','Difference'})
Here, ‘iv’ is the independent variable matrix, composed of the independent variable vectors. This allows a single variable to be passed to any of the curve-fitting (parameter estimation) functions, as their syntax requires, while fitting every independent variable.
Since there are only three parameters, the fminsearch function can likely do a decent approximaton to the desired parameter estimates.
.
More Answers (0)
See Also
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!