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

24 views (last 30 days)
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

Accepted Answer

Greig
Greig on 18 Feb 2015
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 Comments
Greig
Greig on 19 Feb 2015
Edited: Greig on 19 Feb 2015
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.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!