Sum function handle in a for loop
Afficher commentaires plus anciens
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
Plus de réponses (1)
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
le 26 Mai 2021
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!