how to get the function as the sum of other functions?

조회 수: 24 (최근 30일)
Oleksandr Oleksandras
Oleksandr Oleksandras 2015년 2월 17일
댓글: Oleksandr Oleksandras 2015년 3월 2일
I have a function fitfun=@(x)energy(i)-laa(i)*(1-exp(-x)), where x is unknown, energy and laa are arrays of values. I need to obtain expression for the summ of the functions: sumf=@(x)energy(1)-laa(1)*(1-exp(-x))+energy(2)-laa(2)*(1-exp(-x))...energy(N)-laa(N)*(1-exp(-x)). Next I need to minimize the "sumf" i.e. to find "x" which would give the value for total_function ~0. Fminsearch works perfectly for the individual function "fitfun" but not for the total sumf. Here is the script:
>
>syms x;
>> for i=1:N
function=@(x)energy(i)-laa(i)*(1-exp(-x))
sumf=@(x)sumf(x)+fitfun(x)
end
>> [x,fval] = fminsearch(sumf,[0])
Subscript indices must either be real positive integers or logicals.
Error in @(x)sumf(x)+fitfun(x)
Error in @(x)sumf(x)+fitfun(x)
Error in @(x)sumf(x)+fitfun(x)
Error in @(x)sumf(x)+fitfun(x)
Error in @(x)sumf(x)+fitfun(x)
Error in @(x)sumf(x)+fitfun(x)
Error in fminsearch (line 191)
fv(:,1) = funfcn(x,varargin{:});
>>
Thank you

채택된 답변

Greig
Greig 2015년 2월 18일
The easiest way would be to set it up your function as something like...
sumf = @(x) sum(energy - laa .* (1-exp(-x)) )
Then call fminsearch. This also saves on the loop, but make sure that your dimensions of "energy" and "laa" are consistent.
Also, depending on your function values, you may want to minimise the sum of the squares. If the sum is <0 then you will end up far from zero.
  댓글 수: 3
Greig
Greig 2015년 2월 19일
편집: Greig 2015년 2월 19일
This will be because you define the sumf function as
sumf=@(x)sumf(x)+fitfun(x)
which calls itself recursively.
Have you tried defining it as I have above? That is, without the recursive call.
Oleksandr Oleksandras
Oleksandr Oleksandras 2015년 3월 2일
yes it works fine

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by