MATLAB: Fsolve with three anonymous functions

cell arrayfsolvefunction handleMATLAB

Hello everybody,
I can't see why giving a cell array of three separate anonymous as input to fsolve() doesn't work:
a = 6;
f = @(x)[sin(x);x;x*x];
g = @(x) sin(x);
h = @(x) x;
y1 = fsolve(f,a)
y2 = fsolve({g,f},a)
y3 = fsolve({f,g,h},a)
y1 and y2 will be calculated, y3 results in an error:
??? Error using ==> lsqfcnchk at 117
FUN must be a function or an inline object;
What do I miss over here? or, FUN may be a cell array that contains these type of objects.

Best Answer

O.k., Walter thinks we haven't answered your original question, and he may be right. As his comment on your answer shows, the loop can work - but not in the form you have displayed it. If you define a function this way,
function EqSys = makeSystem(N)
EqSys = cell(1,N);
for i=1:N
EqSys{i} = @(x)x^i;
end
and then try these commands
>> EqSys = makeSystem(2)
EqSys =
@(x)(x-i)^i @(x)(x-i)^i
the output is a cell array of function handles that works as in Walter's comment - for example,
>> EqSys{2}(1)
ans =
1
Then if you type
>> fsolve(EqSys,1)
you get an answer of 0 (preceded by a lot of diagnostic statements).
But did you really get the simultaneous solution of these equations? If your function is
function EqSys = makeSystem(N)
EqSys = cell(1,N);
for i=1:N
EqSys{i} = @(x)(x-i)^i;
end
and you enter
>> EqSys = makeSystem(2);
>> fsolve(EqSys,1)
you will get an answer of 1 (which only solves the first equation).
I don't see any way of setting this up using function handles that is worth the trouble. Instead, you could create a function like this:
function y = eqnSystem(x,N)
y = zeros(N,1);
for i=1:N
y(i) = (x(i)-i)^i;
end
which, by the way, assumes that x has as many components as there are equations - a requirement for a well-defined problem. Then
>> x0 = [2 3];
>> f = @(x) eqnSystem(x,N);
>> fsolve(f,x0)
gives the answer
1.0000 2.0075
which is surprisingly inaccurate (but you can improve this by adjusting the options for fsolve).