设为首页收藏本站

EPS数据狗论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1403|回复: 0

MATLAB程序:非线性方程组

[复制链接]

13

主题

152

金钱

235

积分

入门用户

发表于 2018-9-20 14:48:12 | 显示全部楼层 |阅读模式
  1. function [x,FVAL,EXITFLAG,OUTPUT,JACOB] = fsolve(FUN,x,options,varargin)
  2. %优化工具箱函数,可求多元非线性方程组的实根. 用法与fzero类似。
  3. %例 先写一个M函数rooteg4fun.m
  4. %                  function  y=rooteg4fun(x)
  5. %                  y(1)=4*x(1)-x(2)+exp(x(1))/10-1;
  6. %                  y(2)=-x(1)+4*x(2)+x(1).^2/8;
  7. %   使用
  8. %      [x,f,h]=fsolve('rooteg4fun',[0,0]) %初值x(1)=0,x(2)=0
  9. %   x返回解向量,f返回误差向量,h>0表明算法收敛
  10. %   注意:方程变量必须拼成一个向量变量,即用x(1),x(2),...
  11. %
  12. %FSOLVE Solves nonlinear equations by a least squares method.
  13. %
  14. %   FSOLVE solves equations of the form:
  15. %            
  16. %   F(X)=0    where F and X may be vectors or matrices.   
  17. %
  18. %   X=FSOLVE(FUN,X0) starts at the matrix X0 and tries to solve the
  19. %   equations described in FUN. FUN is usually an M-file which returns
  20. %   an evaluation of the equations for a particular value of X: F=FUN(X).
  21. %
  22. %   X=FSOLVE(FUN,X0,OPTIONS) minimizes with the default optimization
  23. %   parameters replaced by values in the structure OPTIONS, an argument
  24. %   created with the OPTIMSET function.  See OPTIMSET for details.  Used
  25. %   options are Display, TolX, TolFun, DerivativeCheck, Diagnostics, Jacobian,
  26. %   JacobPattern, LineSearchType, LevenbergMarquardt, MaxFunEvals, MaxIter,
  27. %   DiffMinChange and DiffMaxChange, LargeScale, MaxPCGIter, PrecondBandWidth,
  28. %   TolPCG, TypicalX. Use the Jacobian option to specify that FUN may be called
  29. %   with two output arguments where the second, J, is the Jacobian matrix:
  30. %   [F,J] = feval(FUN,X). If FUN returns a vector (matrix) of m components when
  31. %   X has length n, then J is an m-by-n matrix where J(i,j) is the partial
  32. %   derivative of F(i) with respect to x(j). (Note that the Jacobian J is the
  33. %   transpose of the gradient of F.)
  34. %
  35. %   X=FSOLVE(FUN,X0,OPTIONS,P1,P2,...) passes the problem-dependent
  36. %   parameters P1,P2,... directly to the function FUN: FUN(X,P1,P2,...).  
  37. %   Pass an empty matrix for OPTIONS to use the default values.
  38. %
  39. %   [X,FVAL]=FSOLVE(FUN,X0,...) returns the value of the objective function
  40. %    at X.
  41. %
  42. %   [X,FVAL,EXITFLAG]=FSOLVE(FUN,X0,...) returns a string EXITFLAG that
  43. %   describes the exit condition of FSOLVE.  
  44. %   If EXITFLAG is:
  45. %      > 0 then FSOLVE converged to a solution X.
  46. %      0   then the maximum number of function evaluations was reached.
  47. %      < 0 then FSOLVE did not converge to a solution.
  48. %
  49. %   [X,FVAL,EXITFLAG,OUTPUT]=FSOLVE(FUN,X0,...) returns a structure OUTPUT
  50. %   with the number of iterations taken in OUTPUT.iterations, the number of
  51. %   function evaluations in OUTPUT.funcCount, the algorithm used in OUTPUT.algorithm,
  52. %   the number of CG iterations (if used) in OUTPUT.cgiterations, and the first-order
  53. %   optimality (if used) in OUTPUT.firstorderopt.
  54. %
  55. %   [X,FVAL,EXITFLAG,OUTPUT,JACOB]=FSOLVE(FUN,X0,...) returns the
  56. %   Jacobian of FUN at X.  

  57. %   Copyright (c) 1990-98 by The MathWorks, Inc.
  58. %   $Revision: 1.26 $  $Date: 1998/10/22 19:28:31 $
  59. %   Andy Grace 7-9-90.

  60. %   Grandfathered FSOLVE call for Optimization Toolbox versions prior to 2.0:
  61. %   [X,OPTIONS]=FSOLVE(FUN,X0,OPTIONS,GRADFUN,P1,P2,...)
  62. %
  63. % ------------Initialization----------------

  64. defaultopt = optimset('display','final','LargeScale','on', ...
  65.    'TolX',1e-6,'TolFun',1e-6,'DerivativeCheck','off',...
  66.    'Jacobian','off','MaxFunEvals','100*numberOfVariables',...
  67.    'Diagnostics','off',...
  68.    'DiffMaxChange',1e-1,'DiffMinChange',1e-8,...
  69.    'PrecondBandWidth',0,'TypicalX','ones(numberOfVariables,1)','MaxPCGIter','max(1,floor(numberOfVariables/2))', ...
  70.    'TolPCG',0.1,'MaxIter',400,'JacobPattern',[], ...
  71.    'LineSearchType','quadcubic','LevenbergMarq','off');
  72. % If just 'defaults' passed in, return the default options in X
  73. if nargin==1 & nargout <= 1 & isequal(FUN,'defaults')
  74.    x = defaultopt;
  75.    return
  76. end

  77. if nargin < 2, error('FSOLVE requires two input arguments');end
  78. if nargin < 3, options=[]; end

  79. % These are added so that we can have the same code as in lsqnonlin which
  80. %  actually has upper and lower bounds.
  81. LB = []; UB = [];

  82. %[x,FVAL,EXITFLAG,OUTPUT,JACOB] = fsolve(FUNin,x,options,varargin)
  83. % Note: don't send varargin in as a comma separated list!!
  84. numargin = nargin; numargout = nargout;
  85. [calltype, GRADFUN, varargin] = parse_call(FUN,options,numargin,numargout,varargin);

  86. if isequal(calltype,'new')  % fsolve version 2.*
  87.    
  88.    xstart=x(:);
  89.    numberOfVariables=length(xstart);
  90.    
  91.    large = 'large-scale';
  92.    medium = 'medium-scale';
  93.    
  94.    l = []; u = [];
  95.    
  96.    options = optimset(defaultopt,options);
  97.    switch optimget(options,'display')
  98.    case {'off','none'}
  99.       verbosity = 0;
  100.    case 'iter'
  101.       verbosity = 2;
  102.    case 'final'
  103.       verbosity = 1;
  104.    case 'testing'
  105.       verbosity = Inf;
  106.    otherwise
  107.       verbosity = 1;
  108.    end
  109.    diagnostics = isequal(optimget(options,'diagnostics','off'),'on');
  110.    
  111.    gradflag =  strcmp(optimget(options,'Jacobian'),'on');
  112.    line_search = strcmp(optimget(options,'largescale','off'),'off'); % 0 means trust-region, 1 means line-search
  113.    
  114.    % Convert to inline function as needed
  115.    if ~isempty(FUN)  % will detect empty string, empty matrix, empty cell array
  116.       [funfcn, msg] = fprefcnchk(FUN,'fsolve',length(varargin),gradflag);
  117.    else
  118.       errmsg = sprintf('%s\n%s', ...
  119.          'FUN must be a function name, valid string expression, or inline object;', ...
  120.          ' or, FUN may be a cell array that contains these type of objects.');
  121.       error(errmsg)
  122.    end
  123.    
  124.    x(:) = xstart;
  125.    switch funfcn{1}
  126.    case 'fun'
  127.       fuser = feval(funfcn{3},x,varargin{:});
  128.       f = fuser(:);
  129.       nfun=length(f);
  130.       JAC = zeros(nfun,numberOfVariables);
  131.    case 'fungrad'
  132.       [fuser,JAC] = feval(funfcn{3},x,varargin{:});
  133.       f = fuser(:);
  134.       nfun=length(f);
  135.    case 'fun_then_grad'
  136.       fuser = feval(funfcn{3},x,varargin{:});
  137.       f = fuser(:);
  138.       JAC = feval(funfcn{4},x,varargin{:});
  139.       nfun=length(f);
  140.       
  141.    otherwise
  142.       error('Undefined calltype in FSOLVE');
  143.    end
  144.    
  145.    % check size of JAC
  146.    [Jrows, Jcols]=size(JAC);
  147.    if Jrows~=nfun | Jcols ~=numberOfVariables
  148.       errstr = sprintf('%s\n%s%d%s%d\n',...
  149.          'User-defined Jacobian is not the correct size:',...
  150.          '    the Jacobian matrix should be ',nfun,'-by-',numberOfVariables);
  151.       error(errstr);
  152.    end
  153.    
  154.    YDATA = []; caller = 'fsolve';
  155.    
  156.    % trustregion and enough equations (as many as variables)
  157.    if ~line_search & nfun >= numberOfVariables
  158.       OUTPUT.algorithm = large;
  159.       
  160.       % trust region and not enough equations -- switch to line_search
  161.    elseif ~line_search & nfun < numberOfVariables
  162.       warnstr = sprintf('%s\n%s\n', ...
  163.          'Large-scale method requires at least as many equations as variables; ',...
  164.          '   switching to line-search method instead.');
  165.       warning(warnstr);
  166.       OUTPUT.algorithm = medium;
  167.       
  168.       % line search and no bounds  
  169.    elseif line_search & isempty(l) & isempty(u)
  170.       OUTPUT.algorithm = medium;
  171.       
  172.       % line search and  bounds  and enough equations, switch to trust region
  173.    elseif line_search & (~isempty(LB) | ~isempty(UB))  & nfun >= numberOfVariables
  174.       warnstr = sprintf('%s\n%s\n', ...
  175.          'Line-search method does not handle bound constraints; ',...
  176.          '   switching to trust-region method instead.');
  177.       warning(warnstr);
  178.       OUTPUT.algorithm = large;
  179.       
  180.       % can't handle this one:   
  181.    elseif line_search & (~isempty(LB) | ~isempty(UB))  & nfun < numberOfVariables
  182.       errstr = sprintf('%s\n%s\n%s\n', ...
  183.          'Line-search method does not handle bound constraints ',...
  184.          '   and trust-region method requires at least as many equations as variables; ',...
  185.          '   aborting.');
  186.       error(errstr);
  187.       
  188.    end
  189.    
  190.    if diagnostics > 0
  191.       % Do diagnostics on information so far
  192.       constflag = 0; gradconstflag = 0; non_eq=0;non_ineq=0;lin_eq=0;lin_ineq=0;
  193.       confcn{1}=[];c=[];ceq=[];cGRAD=[];ceqGRAD=[];
  194.       hessflag = 0; HESS=[];
  195.       msg = diagnose('fsolve',OUTPUT,gradflag,hessflag,constflag,gradconstflag,...
  196.          line_search,options,xstart,non_eq,...
  197.          non_ineq,lin_eq,lin_ineq,LB,UB,funfcn,confcn,f,JAC,HESS,c,ceq,cGRAD,ceqGRAD);
  198.       
  199.    end
  200.    
  201.    % Execute algorithm
  202.    if isequal(OUTPUT.algorithm, large)
  203.       if ~gradflag
  204.          Jstr = optimget(options,'JacobPattern',[]);
  205.          if isempty(Jstr)  
  206.             % Put this code separate as it might generate OUT OF MEMORY error
  207.             Jstr = sparse(ones(Jrows,Jcols));
  208.          end
  209.       else
  210.          Jstr = [];
  211.       end
  212.       l = []; u = []; computeLambda = 0;
  213.       [x,FVAL,LAMBDA,JACOB,EXITFLAG,OUTPUT]=...
  214.          snls(funfcn,x,l,u,verbosity,options,f,JAC,YDATA,caller,Jstr,computeLambda,varargin{:});
  215.    else
  216.       [x,FVAL,JACOB,EXITFLAG,OUTPUT] = ...
  217.          nlsq(funfcn,x,verbosity,options,f,JAC,YDATA,caller,varargin{:});
  218.       
  219.    end
  220.    
  221.    Resnorm = FVAL'*FVAL;  % assumes FVAL still a vector
  222.    if Resnorm > 10*optimget(options,'TolFun',1e-4) & verbosity>0
  223.       if verbosity > 0
  224.          disp('Optimizer is stuck at a minimum that is not a root')
  225.          disp('Try again with a new starting guess')
  226.       end
  227.       EXITFLAG = -1;
  228.    end
  229.    
  230.    % Reset FVAL to shape of the user-function output, fuser
  231.    FVAL = reshape(FVAL,size(fuser));
  232.    
  233.    % end FSOLVE 2.*
  234. else % version 1.5 FSOLVE
  235.    
  236.    if length(options)<5;
  237.       options(5)=0;
  238.    end
  239.    % Switch methods making Gauss Newton the default method.
  240.    if options(5)==0; options(5)=1; else options(5)=0; end
  241.    
  242.    % Convert to inline function as needed.
  243.    if ~isempty(FUN)
  244.       [funfcn, msg] = fcnchk(FUN,length(varargin));
  245.       if ~isempty(msg)
  246.          error(msg);
  247.       end
  248.    else
  249.       error('FUN must be a function name or valid expression.')
  250.    end
  251.    
  252.    if ~isempty(GRADFUN)
  253.       [gradfcn, msg] = fcnchk(GRADFUN,length(varargin));
  254.       if ~isempty(msg)
  255.          error(msg);
  256.       end
  257.    else
  258.       gradfcn = [];
  259.    end
  260.    
  261.    [x,options] = nlsqold(funfcn,x,options,gradfcn,varargin{:});
  262.    
  263.    if options(8)>10*options(3) & options(1)>0
  264.       disp('Optimizer is stuck at a minimum that is not a root')
  265.       disp('Try again with a new starting guess')
  266.    end
  267.    
  268.    % Set the second output argument FVAL to be options as in old calling syntax
  269.    FVAL = options;
  270.    
  271.    % end fsolve version 1.5.*
  272.    
  273. end

  274. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  275. function [calltype, GRADFUN, otherargs] = parse_call(FUN,options,numargin,numargout,otherargs)
  276. % PARSE_CALL Determine which calling syntax is being used: the FSOLVE prior to 2.0, or
  277. %    in version 2.0 or later of the Toolbox.
  278. %    old call: [X,OPTIONS]=FSOLVE(FUN,X0,OPTIONS,GRADFUN,varargin)
  279. %    new call: [X,FVAL,EXITFLAG,OUTPUT,JACOB]=FSOLVE(FUN,X0,OPTIONS,varargin)

  280. if numargout > 2               % [X,FVAL,EXITFLAG,...]=FSOLVE (...)
  281.    calltype = 'new';
  282.    GRADFUN = [];
  283. elseif isa(FUN,'cell')         % FUN == {...}
  284.    calltype = 'new';
  285.    GRADFUN = [];
  286. elseif ~isempty(options) & isa(options,'double')   % OPTIONS == scalar or and array
  287.    calltype = 'old';
  288.    if length(otherargs) > 0
  289.       GRADFUN = otherargs{1};
  290.       otherargs = otherargs(2:end);
  291.    else
  292.       GRADFUN = [];
  293.    end
  294. elseif isa(options,'struct')   % OPTIONS has fields
  295.    calltype = 'new';
  296.    GRADFUN = [];
  297. else                           % Ambiguous
  298.    warnstr = sprintf('%s\n%s\n%s\n',...
  299.       'Cannot determine from calling sequence whether to use new (2.0 or later) FSOLVE ', ...
  300.       'function or grandfathered FSOLVE function.  Assuming new syntax; if call was grandfathered', ...
  301.       'FSOLVE syntax, this may give unexpected results.');
  302.    warning(warnstr)
  303.    calltype = 'new';
  304.    GRADFUN = [];
  305. end

  306. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  307. function [allfcns,msg] = fprefcnchk(funstr,caller,lenVarIn,gradflag)
  308. %PREFCNCHK Pre- and post-process function expression for FUNCHK.
  309. %   [ALLFCNS,MSG] = PREFUNCHK(FUNSTR,CALLER,lenVarIn,GRADFLAG) takes
  310. %   the (nonempty) expression FUNSTR from CALLER with LenVarIn extra arguments,
  311. %   parses it according to what CALLER is, then returns a string or inline
  312. %   object in ALLFCNS.  If an error occurs, this message is put in MSG.
  313. %
  314. %   ALLFCNS is a cell array:
  315. %    ALLFCNS{1} contains a flag
  316. %    that says if the objective and gradients are together in one function
  317. %    (calltype=='fungrad') or in two functions (calltype='fun_then_grad')
  318. %    or there is no gradient (calltype=='fun'), etc.
  319. %    ALLFCNS{2} contains the string CALLER.
  320. %    ALLFCNS{3}  contains the objective function
  321. %    ALLFCNS{4}  contains the gradient function (transpose of Jacobian).
  322. %  
  323. %    NOTE: we assume FUNSTR is nonempty.
  324. % Initialize
  325. msg='';
  326. allfcns = {};
  327. funfcn = [];
  328. gradfcn = [];

  329. if gradflag
  330.    calltype = 'fungrad';
  331. else
  332.    calltype = 'fun';
  333. end

  334. % {fun}
  335. if isa(funstr, 'cell') & length(funstr)==1
  336.    % take the cellarray apart: we know it is nonempty
  337.    if gradflag
  338.       calltype = 'fungrad';0
  339.    end
  340.    [funfcn, msg] = fcnchk(funstr{1},lenVarIn);
  341.    if ~isempty(msg)
  342.       error(msg);
  343.    end
  344.    
  345.    % {fun,[]}      
  346. elseif isa(funstr, 'cell') & length(funstr)==2 & isempty(funstr{2})
  347.    if gradflag
  348.       calltype = 'fungrad';
  349.    end
  350.    [funfcn, msg] = fcnchk(funstr{1},lenVarIn);
  351.    if ~isempty(msg)
  352.       error(msg);
  353.    end  
  354.    
  355.    % {fun, grad}   
  356. elseif isa(funstr, 'cell') & length(funstr)==2 % and ~isempty(funstr{2})
  357.    
  358.    [funfcn, msg] = fcnchk(funstr{1},lenVarIn);
  359.    if ~isempty(msg)
  360.       error(msg);
  361.    end  
  362.    [gradfcn, msg] = fcnchk(funstr{2},lenVarIn);
  363.    if ~isempty(msg)
  364.       error(msg);
  365.    end
  366.    calltype = 'fun_then_grad';
  367.    if ~gradflag
  368.       warnstr = ...
  369.          sprintf('%s\n%s\n%s\n','Jacobian function provided but OPTIONS.Jacobian=''off'';', ...
  370.          '  ignoring Jacobian function and using finite-differencing.', ...
  371.          '  Rerun with OPTIONS.Jacobian=''on'' to use Jacobian function.');
  372.       warning(warnstr);
  373.       calltype = 'fun';
  374.    end   
  375.    
  376. elseif ~isa(funstr, 'cell')  %Not a cell; is a string expression, function name string or inline object
  377.    [funfcn, msg] = fcnchk(funstr,lenVarIn);
  378.    if ~isempty(msg)
  379.       error(msg);
  380.    end   
  381.    if gradflag % gradient and function in one function/M-file
  382.       gradfcn = funfcn; % Do this so graderr will print the correct name
  383.    end  
  384. else
  385.    errmsg = sprintf('%s\n%s', ...
  386.       'FUN must be a function name, valid string expression, or inline object;', ...
  387.       ' or, FUN may be a cell array that contains these type of objects.');
  388.    error(errmsg)
  389. end

  390. allfcns{1} = calltype;
  391. allfcns{2} = caller;
  392. allfcns{3} = funfcn;
  393. allfcns{4} = gradfcn;
  394. allfcns{5}=[];

复制代码


FSOLVE.rar

4.96 KB, 下载次数: 0, 下载积分: 贡献 -1

售价: 1 金钱  [记录]  [购买]

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

客服中心
关闭
在线时间:
周一~周五
8:30-17:30
QQ群:
653541906
联系电话:
010-85786021-8017
在线咨询
客服中心

意见反馈|网站地图|手机版|小黑屋|EPS数据狗论坛 ( 京ICP备09019565号-3 )   

Powered by BFIT! X3.4

© 2008-2028 BFIT Inc.

快速回复 返回顶部 返回列表