function [F,J] = nleqwj(x);
% computes the objective function values and the Jacobian.
%
% Consider the problem of finding a solution to a system of nonlinear 
% equations whose Jacobian is sparse. The dimension of the problem in 
% this example is 1000. The goal is to find x such that F(x) = 0. 
% Assuming n = 1000, the nonlinear equations are:
% F(1)=3(x_1)-2(x_1)^2-2(x_2)+1
% F(i)=3(x_i)-2(x_i)^2-2(x_i-1)-2(x_i+1)+1
% F(n)=3(x_n)-2(x_n)^2-(x_n-1)+1
% To solve a large nonlinear system of equations, F(x) = 0, use the 
% large-scale method available in fsolve.

% Evaluate the vector function
n = length(x);
F = zeros(n,1);
i = 2:(n-1);
F(i) = (3-2*x(i)).*x(i)-x(i-1)-2*x(i+1)+ 1;
F(n) = (3-2*x(n)).*x(n)-x(n-1) + 1;
F(1) = (3-2*x(1)).*x(1)-2*x(2) + 1;
% Evaluate the Jacobian if nargout > 1
if nargout > 1
   d = -4*x + 3*ones(n,1); D = sparse(1:n,1:n,d,n,n);
   c = -2*ones(n-1,1); C = sparse(1:n-1,2:n,c,n,n);
   e = -ones(n-1,1); E = sparse(2:n,1:n-1,e,n,n);
      J = C + D + E;
end

% The MathWorks, Matlab7. Copyright (c).