Sum function handle in a for loop

조회 수: 18 (최근 30일)
Clément Métayer
Clément Métayer 2021년 5월 26일
댓글: Walter Roberson 2021년 5월 26일
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

채택된 답변

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 5월 26일
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
Clément Métayer
Clément Métayer 2021년 5월 26일
Thx for your answer !!
Walter Roberson
Walter Roberson 2021년 5월 26일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2021년 5월 26일
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
Clément Métayer
Clément Métayer 2021년 5월 26일
Thank you for your answer, it helps me. I accepted the other answer just because i can only accept one.
Regards

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Conversion Between Symbolic and Numeric에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by