MATLAB: Summation of functions in a loop

summation functions loop

Hi there, I would like to create functions and then sum them up in a loop. Then use an optimizer to find the minimum of the summation. The functions are the same but I need them to have independent variables.
for example: I need a "matrix" of functions
A=[@(x)(x(1)-S(1))^2, @(x)(x(2)-S(2))^2,..., @(x)(x(n)-S(n))^2]
,where S a (1xn) matrix. Then summing all of the above functions to get the minimum
x0 = [0,0,...n];
x = fminsearch(sum(A(:)),x0)
The above code does not work but I am just posting it so you get a better idea of what I am looking for. Thank you

Best Answer

Creating an array of functions is a red herring. You just need one simple array, inside one function:
>> fun = @(x) sum((x-5).^2);
>> x0 = [0,0,0,0];
>> fminsearch(fun,x0)
ans =
4.9997 5.0001 5.0001 5.0002
If you really want each "function" to be different, then you still only need one matrix inside one function:
>> fun = @(x) sum([(x(1)-3)^2,(x(2)-5)^2,(x(3)-8)^2,(x(4))^2]);
>> x0 = [0,0,0,0];
>> fminsearch(fun,x0)
ans =
2.9998e+000 4.9999e+000 7.9998e+000 -1.3034e-004
Trying to create an array of functions is possible (just put them into a cell array), but will likely be a total waste of your time. After all, fminsearch only accepts one function, so why not simply define one function ?