Oh! I think I understand why you're doing what you're doing. You've been getting the error message,
??? Error using ==> lsqfcnchk at 117
FUN must be a function or an inline object;
or, FUN may be a cell array that contains these type of objects.
so you've been thinking FUN can be a cell array. Then you type "help lsqnonlin," and you read
X = LSQNONLIN(FUN,X0) starts at the matrix X0 and finds a minimum X to
the sum of squares of the functions in FUN.
and that phrase "the functions in FUN" leads you to believe that there are
multiple functions.
All this is extremely misleading. FUN is
one function. It
returns a vector. Why the MATLAB documentation confuses the issue, I do not know.
Here's a correct version of what I think you were attempting with your last code:
% answer.m
function answer()
[x, resnorm] = lsqnonlin(@residuals, 10);
fprintf('x = %g\nresnorm = %g\n', x, resnorm);
end
function r = residuals(x)
for i=1:3
r(i) = x^i;
end
end
Note that the answer is trivial. We're looking for the number "x" that minimizes (x^1)^2 + (x^2)^2 + (x^3)^3, and that number is of course zero. Note also that "residuals" can be written more efficiently than above as,
function r = residuals(x)
r = x.^[1:3];
end
and that, if you really want, you can do everything with the one-liner,
[x, resnorm] = lsqnonlin(@(x)(x.^[1:3]), 10);
Finally, I think you may also be a bit confused about cell arrays. The syntax, "opt = {3};" does not declare a cell array of size 3x1 or 1x3. It creates a cell array of size 1x1, containing the value 3. For an example of what the curly brackets do in this context, consider the statement "opt = {[1;2], eye(2), 1};" this makes a 1x3 cell array containing a 2x1 vector, a 2x2 matrix, and a scalar.
I hope that helps.
Edited by Emergent, 12 October 2012 - 11:38 AM.