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

31 visualizzazioni (ultimi 30 giorni)
Oleksandr Oleksandras il 17 Feb 2015
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,)
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
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Greig il 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 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
Greig il 19 Feb 2015
Modificato: Greig il 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.
Oleksandr Oleksandras il 2 Mar 2015
yes it works fine

Accedi per commentare.

### Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!