Sum function handle in a for loop
6 views (last 30 days)
Show older comments
Clément Métayer
on 26 May 2021
Commented: Walter Roberson
on 26 May 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
0 Comments
Accepted Answer
Sulaymon Eshkabilov
on 26 May 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 Comments
Walter Roberson
on 26 May 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.
More Answers (1)
Walter Roberson
on 26 May 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)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!