Sum function handle in a for loop

18 vues (au cours des 30 derniers jours)
Clément Métayer
Clément Métayer le 26 Mai 2021
Commenté : Walter Roberson le 26 Mai 2021
Hi, Im trying to sum function handle for fitting data with the function fitnlm.
My non-linear-model is:
sigma=2;
mu=[1 2 3 4];
modelfun = @(b,x) b(1) * exp(-(x(:, 1) - mu(1)).^2/sigma.^2) + b(2) * exp(-(x(:, 1) - mu(2)).^2/sigma.^2) ...
+ b(3) * exp(-(x(:, 1) - mu(3)).^2/sigma.^2) + b(4) * exp(-(x(:, 1) - mu(4)).^2/sigma.^2);
But i want to sum all this expressions in a for loop because in general i do not know the number of gaussian im trying to fit.
I tried things like this:
M = b(1) .* exp(-(x(:, 1) - mu(1)).^2/sigma.^2);
for k = 2:N
add = @(b,x) b(k) .* exp(-(x(:, 1) - mu(k)).^2/sigma.^2);
M = M + add;
end
and many variants but none of them did work.
I'm sure there are some ways to sum up function handle in for loop but i can't figure out.
Regards

Réponse acceptée

Sulaymon Eshkabilov
Sulaymon Eshkabilov le 26 Mai 2021
Hi,
Using symbolics might be an easy solution here:
sigma=2;
syms x
syms b [1 4]
syms mu [1 4 ]
M =(b(1) .* exp(-(x - mu(1)).^2/sigma.^2));
for k = 2:numel(mu)
M = M+ b(k) .* exp(-(x - mu(k)).^2/sigma.^2);
end
% Then you can substitte the values of mu, b using subs()
Good luck
  2 commentaires
Clément Métayer
Clément Métayer le 26 Mai 2021
Thx for your answer !!
Walter Roberson
Walter Roberson le 26 Mai 2021
After you have the symbolic M then use matlabFunction() to create an anonymous function for use in fitting. Be sure to use the 'vars' option so that the inputs will be in the correct order.

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 26 Mai 2021
M = @(b,x) b(1) .* exp(-(x(:, 1) - mu(1)).^2/sigma.^2);
for k = 2:N
add = @(b,x) b(k) .* exp(-(x(:, 1) - mu(k)).^2/sigma.^2);
M = @(b,x) M(b,x) + add(b,x);
end
At the end if you look at M you will see just
M(b,x) + add(b,x)
so it will look like it did not work.
The result will not be efficient.
You should consider other routes, such as
ROW = @(V) reshape(V,1,[]);
M = @(b,x) sum(ROW(b) .* exp((x(:,1) - ROW(mu)).^2/sigma.^2),2)
This requires that b and mu are the same length. It does not assume that b and mu are row vectors (the code could be made slightly more efficient if you were willing to fix the orientation of b and mu, especially if you knew for sure they were row vectors)
  1 commentaire
Clément Métayer
Clément Métayer le 26 Mai 2021
Thank you for your answer, it helps me. I accepted the other answer just because i can only accept one.
Regards

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by