Speeding up calculation and removing symbol operation for modelization

1 vue (au cours des 30 derniers jours)
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

Réponse acceptée

Bjorn Gustavsson
Bjorn Gustavsson le 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 commentaires
Antoine Enel
Antoine Enel le 15 Oct 2020
Thanks for your help, this is a great solution.
Have a good day,
Antoine Enel
Bjorn Gustavsson
Bjorn Gustavsson le 15 Oct 2020
My pleasure, and you too have a good day.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by