Speeding up calculation and removing symbol operation for modelization
1 view (last 30 days)
Show older comments
Antoine Enel
on 14 Oct 2020
Commented: Bjorn Gustavsson
on 15 Oct 2020
Hello everyone,
I'm having an issue with modelization on R2018a. I'm trying to fit a rectangular matrix M by a function with two variables, x and y by using least squares method. x and y variables are contained into X and Y matrixes, which match the size of M.
Function is
B=sym('b',[1 3]);
func=@(B,x,y) B(3)*x+B(1)*exp(B(2)./y);
B being the model coefficients. I've declared it as a symbol.
The rectangular matrix contains NaN values that need to be ignored during the calculation, without any constrictions on the number or location of NaN values.
Solution I've found is to get an index of the matrix
idx=isfinite(M);
then to calculate the least squares estimator for every finite value of M,sum it up and find its minimum.
lsq_estimator=sym(zeros(size(M,1),size(M,2)))
for i=1:size(M,1)
for j=1:size(M,2)
if idx(i,j) == 1
lsq_estimator(i,j)=M(i,j)-func(B,X(i),Y(j));
end
end
end
OLS=sum(sum(lsq_estimator));
OLS= matlabFunction(OLS,'vars',{B});
B_coeff=fminsearch(OLS,B_0)
The main issue is with B being a symbol, calculation slows down a lot. Is there a way to do the same type of calculation without B being a symbol ?
I've tried to declare the least squares estimator as an anonymous function, but then the least squares estimators cannot be summed together into the OLS fonction.
Thanks a lot,
Best regards
Antoine Enel
0 Comments
Accepted Answer
Bjorn Gustavsson
on 14 Oct 2020
You can simply define your model-function something like this:
func = @(B,x,y) B(3)*x+B(1)*exp(B(2)./y);
There is no reason to make a detour by symbolic variables.
Then you can simplify the definition of your error-function too. Perhaps something like this:
err_fcn = @(pars,M,X,Y,f) sum((M(:) - f(pars,X(:),Y(:) ) ).^2,'omitnan');
That error-function you can minimize with fminsearch:
Bbest = fminsearch(@(pars) err_fcn(pars,M,X,Y,func),B_guess)
The dynamic function-declaration, function-handle-argument and anonymous functions lets you define a rather general error-function where you send in the independent variables and the function-parameters and the function together with the variable to fit to. This is rather nifty...
HTH
2 Comments
More Answers (0)
See Also
Categories
Find more on Symbolic Math 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!