当前位置: 首页 > news >正文

26 用lsqnonlin求解最小二乘问题(matlab程序)

1.简述

      

函数语法
x = lsqnonlin(fun,x0)
函数用于:

解决非线性最小二乘(非线性数据拟合)问题
解决非线性最小二乘曲线拟合问题的形式

变量x的约束上下限为ub和lb,

x = lsqnonlin(fun,x0)从x0点开始,找到fun中描述的函数的最小平方和。函数fun应该返回一个向量(或数组),而不是值的平方和。(该算法隐式地计算了fun(x)元素的平方和。)
 

2.代码

主程序:

%%  用lsqnonlin求解最小二乘问题
clear all
x0 = [0.3 0.4];                        % 初值点
[x,resnorm] = lsqnonlin(@f1211,x0)     % 调用最优化函数求  x  和  平方和残差

子程序:

function [xCurrent,Resnorm,FVAL,EXITFLAG,OUTPUT,LAMBDA,JACOB] = lsqnonlin(FUN,xCurrent,LB,UB,options,varargin)
%LSQNONLIN solves non-linear least squares problems.
%   LSQNONLIN attempts to solve problems of the form:
%   min  sum {FUN(X).^2}    where X and the values returned by FUN can be   
%    X                      vectors or matrices.
%
%   LSQNONLIN implements two different algorithms: trust region reflective
%   and Levenberg-Marquardt. Choose one via the option Algorithm: for
%   instance, to choose Levenberg-Marquardt, set 
%   OPTIONS = optimoptions('lsqnonlin', 'Algorithm','levenberg-marquardt'), 
%   and then pass OPTIONS to LSQNONLIN.
%    
%   X = LSQNONLIN(FUN,X0) starts at the matrix X0 and finds a minimum X to 
%   the sum of squares of the functions in FUN. FUN accepts input X 
%   and returns a vector (or matrix) of function values F evaluated
%   at X. NOTE: FUN should return FUN(X) and not the sum-of-squares 
%   sum(FUN(X).^2)). (FUN(X) is summed and squared implicitly in the
%   algorithm.) 
%
%   X = LSQNONLIN(FUN,X0,LB,UB) defines a set of lower and upper bounds on
%   the design variables, X, so that the solution is in the range LB <= X
%   <= UB. Use empty matrices for LB and UB if no bounds exist. Set LB(i)
%   = -Inf if X(i) is unbounded below; set UB(i) = Inf if X(i) is
%   unbounded above.
%
%   X = LSQNONLIN(FUN,X0,LB,UB,OPTIONS) minimizes with the default
%   optimization parameters replaced by values in OPTIONS, an argument
%   created with the OPTIMOPTIONS function. See OPTIMOPTIONS for details.
%   Use the SpecifyObjectiveGradient option to specify that FUN also
%   returns a second output argument J that is the Jacobian matrix at the
%   point X. If FUN returns a vector F of m components when X has length n,
%   then J is an m-by-n matrix where J(i,j) is the partial derivative of
%   F(i) with respect to x(j). (Note that the Jacobian J is the transpose
%   of the gradient of F.)
%
%   X = LSQNONLIN(PROBLEM) solves the non-linear least squares problem 
%   defined in PROBLEM. PROBLEM is a structure with the function FUN in 
%   PROBLEM.objective, the start point in PROBLEM.x0, the lower bounds in 
%   PROBLEM.lb, the upper bounds in PROBLEM.ub, the options structure in 
%   PROBLEM.options, and solver name 'lsqnonlin' in PROBLEM.solver. Use 
%   this syntax to solve at the command line a problem exported from 
%   OPTIMTOOL. 
%
%   [X,RESNORM] = LSQNONLIN(FUN,X0,...) returns 
%   the value of the squared 2-norm of the residual at X: sum(FUN(X).^2). 
%
%   [X,RESNORM,RESIDUAL] = LSQNONLIN(FUN,X0,...) returns the value of the 
%   residual at the solution X: RESIDUAL = FUN(X).
%
%   [X,RESNORM,RESIDUAL,EXITFLAG] = LSQNONLIN(FUN,X0,...) returns an
%   EXITFLAG that describes the exit condition. Possible values of EXITFLAG
%   and the corresponding exit conditions are listed below. See the
%   documentation for a complete description.
%
%     1  LSQNONLIN converged to a solution.
%     2  Change in X too small.
%     3  Change in RESNORM too small.
%     4  Computed search direction too small.
%     0  Too many function evaluations or iterations.
%    -1  Stopped by output/plot function.
%    -2  Bounds are inconsistent.
%
%   [X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT] = LSQNONLIN(FUN,X0,...) returns a 
%   structure OUTPUT with the number of iterations taken in
%   OUTPUT.iterations, the number of function evaluations in
%   OUTPUT.funcCount, the algorithm used in OUTPUT.algorithm, the number
%   of CG iterations (if used) in OUTPUT.cgiterations, the first-order
%   optimality (if used) in OUTPUT.firstorderopt, and the exit message in
%   OUTPUT.message.
%
%   [X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT,LAMBDA] = LSQNONLIN(FUN,X0,...) 
%   returns the set of Lagrangian multipliers, LAMBDA, at the solution: 
%   LAMBDA.lower for LB and LAMBDA.upper for UB.
%
%   [X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT,LAMBDA,JACOBIAN] = LSQNONLIN(FUN,
%   X0,...) returns the Jacobian of FUN at X.   
%
%   Examples
%     FUN can be specified using @:
%        x = lsqnonlin(@myfun,[2 3 4])
%
%   where myfun is a MATLAB function such as:
%
%       function F = myfun(x)
%       F = sin(x);
%
%   FUN can also be an anonymous function:
%
%       x = lsqnonlin(@(x) sin(3*x),[1 4])
%
%   If FUN is parameterized, you can use anonymous functions to capture the 
%   problem-dependent parameters. Suppose you want to solve the non-linear 
%   least squares problem given in the function myfun, which is 
%   parameterized by its second argument c. Here myfun is a MATLAB file 
%   function such as
%
%       function F = myfun(x,c)
%       F = [ 2*x(1) - exp(c*x(1))
%             -x(1) - exp(c*x(2))
%             x(1) - x(2) ];
%
%   To solve the least squares problem for a specific value of c, first 
%   assign the value to c. Then create a one-argument anonymous function 
%   that captures that value of c and calls myfun with two arguments. 
%   Finally, pass this anonymous function to LSQNONLIN:
%
%       c = -1; % define parameter first
%       x = lsqnonlin(@(x) myfun(x,c),[1;1])
%
%   See also OPTIMOPTIONS, LSQCURVEFIT, FSOLVE, @, INLINE.

%   Copyright 1990-2018 The MathWorks, Inc.

% ------------Initialization----------------
defaultopt = struct(...
    'Algorithm','trust-region-reflective',...
    'DerivativeCheck','off',...
    'Diagnostics','off',...
    'DiffMaxChange',Inf,...
    'DiffMinChange',0,...
    'Display','final',...
    'FinDiffRelStep', [], ...
    'FinDiffType','forward',...
    'FunValCheck','off',...
    'InitDamping', 0.01, ...
    'Jacobian','off',...
    'JacobMult',[],... 
    'JacobPattern','sparse(ones(Jrows,Jcols))',...
    'MaxFunEvals',[],...
    'MaxIter',400,...
    'MaxPCGIter','max(1,floor(numberOfVariables/2))',...
    'OutputFcn',[],...
    'PlotFcns',[],...
    'PrecondBandWidth',Inf,...
    'ScaleProblem','none',...
    'TolFun', 1e-6,... 
    'TolFunValue', 1e-6, ...
    'TolPCG',0.1,...
    'TolX',1e-6,...
    'TypicalX','ones(numberOfVariables,1)',...
    'UseParallel',false );

% If just 'defaults' passed in, return the default options in X
if nargin==1 && nargout <= 1 && strcmpi(FUN,'defaults')
   xCurrent = defaultopt;
   return
end

if nargin < 5
    options = [];
    if nargin < 4
        UB = [];
        if nargin < 3
            LB = [];
        end
    end
end

problemInput = false;
if nargin == 1
    if isa(FUN,'struct')
        problemInput = true;
        [FUN,xCurrent,LB,UB,options] = separateOptimStruct(FUN);
    else % Single input and non-structure.
        error(message('optim:lsqnonlin:InputArg'));
    end
end

% No options passed. Set options directly to defaultopt after
allDefaultOpts = isempty(options);

% Prepare the options for the solver
options = prepareOptionsForSolver(options, 'lsqnonlin');

% Set options to default if no options were passed.
if allDefaultOpts
    % Options are all default
    options = defaultopt;
end

if nargin < 2 && ~problemInput
  error(message('optim:lsqnonlin:NotEnoughInputs'))
end

% Check for non-double inputs
msg = isoptimargdbl('LSQNONLIN', {'X0','LB','UB'}, ...
                               xCurrent,LB,  UB);
if ~isempty(msg)
    error('optim:lsqnonlin:NonDoubleInput',msg);
end

caller = 'lsqnonlin'; 
[funfcn,mtxmpy,flags,sizes,~,xstart,lb,ub,EXITFLAG,Resnorm,FVAL,LAMBDA, ...
    JACOB,OUTPUT,earlyTermination] = lsqnsetup(FUN,xCurrent,LB,UB,options,defaultopt, ...
    allDefaultOpts,caller,nargout,length(varargin));
if earlyTermination
    return % premature return because of problem detected in lsqnsetup()
end

xCurrent(:) = xstart; % reshape back to user shape before evaluation
% Catch any error in user objective during initial evaluation only
switch funfcn{1}
    case 'fun'
        try
            initVals.F = feval(funfcn{3},xCurrent,varargin{:});
        catch userFcn_ME
            optim_ME = MException('optim:lsqnonlin:InvalidFUN', ...
                getString(message('optim:lsqnonlin:InvalidFUN')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
        end
        initVals.J = [];
    case 'fungrad'
        try
            [initVals.F,initVals.J] = feval(funfcn{3},xCurrent,varargin{:});
        catch userFcn_ME
            optim_ME = MException('optim:lsqnonlin:InvalidFUN', ...
                getString(message('optim:lsqnonlin:InvalidFUN')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
        end
    case 'fun_then_grad'
        try
            initVals.F = feval(funfcn{3},xCurrent,varargin{:});
        catch userFcn_ME
            optim_ME = MException('optim:lsqnonlin:InvalidFUN', ...
                getString(message('optim:lsqnonlin:InvalidFUN')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
        end
        try    
            initVals.J = feval(funfcn{4},xCurrent,varargin{:});
        catch userFcn_ME
            optim_ME = MException('optim:lsqnonlin:InvalidFUN', ...
                getString(message('optim:lsqnonlin:InvalidJacobFun')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
        end
    otherwise
        error(message('optim:lsqnonlin:UndefCallType'))
end

% Check for non-double data typed values returned by user functions 
if ~isempty( isoptimargdbl('LSQNONLIN', {'F','J'}, initVals.F, initVals.J) )
    error('optim:lsqnonlin:NonDoubleFunVal',getString(message('optimlib:commonMsgs:NonDoubleFunVal','LSQNONLIN')));
end

% Flag to determine whether to look up the exit msg.
flags.makeExitMsg = logical(flags.verbosity) || nargout > 4;

[xCurrent,Resnorm,FVAL,EXITFLAG,OUTPUT,LAMBDA,JACOB] = ...
   lsqncommon(funfcn,xCurrent,lb,ub,options,defaultopt,allDefaultOpts,caller,...
              initVals,sizes,flags,mtxmpy,varargin{:});
          

3.运行结果

 

相关文章:

26 用lsqnonlin求解最小二乘问题(matlab程序)

1.简述 函数语法 x lsqnonlin(fun,x0) 函数用于&#xff1a; 解决非线性最小二乘(非线性数据拟合)问题 解决非线性最小二乘曲线拟合问题的形式 变量x的约束上下限为ub和lb&#xff0c; x lsqnonlin(fun,x0)从x0点开始&#xff0c;找到fun中描述的函数的最小平方和。函数fu…...

Verilog语法学习——LV6_多功能数据处理器

LV6_多功能数据处理器 题目来源于牛客网 [牛客网在线编程_Verilog篇_Verilog快速入门 (nowcoder.com)](https://www.nowcoder.com/exam/oj?page1&tabVerilog篇&topicId301) 题目 描述 根据指示信号select的不同&#xff0c;对输入信号a,b实现不同的运算。输入信号a…...

发送信息----策略模式

发送信息----策略模式 发送信息 发送信息 发送信息到手机、邮箱等&#xff0c;可扩展 package mainimport ("errors""fmt" )type PushContext struct {Phone, Email, Message stringTage int }type PaymentStrategy interface {Push(*P…...

PySpark介绍与安装

Spark是什么 定义&#xff1a;Apache Spark是用于大规模数据&#xff08;large-scala data&#xff09;处理的统一&#xff08;unified&#xff09;分析引擎。 简单来说&#xff0c;Spark是一款分布式的计算框架&#xff0c;用于调度成百上千的服务器集群&#xff0c;计算TB、…...

细讲TCP三次握手四次挥手(三)

TCP/IP 协议族 在互联网使用的各种协议中最重要和最著名的就是 TCP/IP 两个协议。现在人们经常提到的 TCP/IP 并不一定是单指 TCP 和 IP 这两个具体的协议&#xff0c;而往往是表示互联网所使用的整个 TCP/IP 协议族。 互联网协议套件&#xff08;英语&#xff1a;Internet Pr…...

vue 组件中 data 为什么必须是函数

在Vue组件中&#xff0c;data选项为什么必须是函数而不是对象的原因是为了确保每个组件实例都拥有独立的数据副本。 当data选项是一个对象时&#xff0c;如果你有多个相同组件的实例&#xff0c;它们会共享同一个对象引用&#xff0c;这意味着一个组件的数据变化会影响到其他相…...

从零开始学python(十二)如何成为一名优秀的爬虫工程师

前言 回顾之前讲述了python语法编程 必修入门基础和网络编程&#xff0c;多线程/多进程/协程等方面的内容&#xff0c;后续讲到了数据库编程篇MySQL&#xff0c;Redis&#xff0c;MongoDB篇&#xff0c;和机器学习&#xff0c;全栈开发&#xff0c;数据分析前面没看的也不用往…...

为高性能计算构建,由亚马逊云科技Amazon Graviton3E驱动的最新实例正式可用

亚马逊云科技宣布两款基于最新一代自研芯片Amazon Graviton3E的新实例Amazon Elastic Compute Cloud&#xff08;Amazon EC2&#xff09;Hpc7g和Amazon EC2 C7gn正式可用。 其中&#xff0c;Hpc7g实例专为计算和网络密集型高性能计算&#xff08;HPC&#xff09;工作负载而构建…...

BUUCTF题目Crypto部分wp(持续更新)

Url编码 题目密文是%66%6c%61%67%7b%61%6e%64%20%31%3d%31%7d&#xff0c;根据题目名字使用python的urllib模块解码即可。flag{and 11} from urllib.parse import quote, unquotec r%66%6c%61%67%7b%61%6e%64%20%31%3d%31%7d m unquote(c, encodingutf-8) print(m)c2 quot…...

A Generalized Loss Function for Crowd Counting and Localization阅读笔记

简单来说&#xff0c;就是用了UOT来解决人群计数问题 代码&#xff1a;https://github.com/jia-wan/GeneralizedLoss-Counting-Pytorch.git 我改了一点的&#xff1a;https://github.com/Nightmare4214/GeneralizedLoss-Counting-Pytorch.git loss 设density map为 A { ( a…...

SocketD协议单链接双向RPC模式怎么实现

SocketD是一个基于Socket的通信框架&#xff0c;支持单链接双向RPC模式。在实现单链接双向RPC模式时&#xff0c;需要按照一定的协议进行通信&#xff0c;以下是一个简单的实现示例&#xff1a; 定义通信协议&#xff1a;首先&#xff0c;需要定义客户端和服务端之间的通信协议…...

apache poi 设置背景颜色

apache poi 设置背景颜色 要设置 Apache POI 中 HSSFCellStyle 的背景颜色&#xff0c;你可以按照以下步骤进行操作&#xff1a; 首先&#xff0c;创建一个 HSSFWorkbook 对象来表示你的 Excel 工作簿&#xff1a; HSSFWorkbook workbook new HSSFWorkbook();然后&#xff…...

Vue2-Vue3组件间通信-EventBus方式-函数封装

Vue3中采用EventBus方式进行组件间通信与Vue2有一定区别 1.创建EventBus 在Vue2中&#xff0c;我们可以在main.js中创建一个全局的EventBus&#xff0c;代码如下&#xff1a; // EventBus.js import Vue from vue const EventBus new Vue() export default EventBus// main.…...

【SpringBoot】| SpringBoot 和 web组件

目录 一&#xff1a;SpringBoot 和 web组件 1. SpringBoot中使用拦截器&#xff08;重点&#xff09; 2. SpringBoot中使用Servlet 3. SpringBoot中使用过滤器&#xff08;重点&#xff09; 4. 字符集过滤器的应用 一&#xff1a;SpringBoot 和 web组件 1. SpringBoot中使…...

dflow工作流使用1——架构和基本概念

对于容器技术、工作流等概念完全不懂的情况下理解dflow的工作方式会很吃力&#xff0c;这里记录一下个人理解。 dflow涉及的基本概念 工作流的概念很好理解&#xff0c;即某个项目可以分为多个步骤&#xff0c;每个步骤可以实现独立运行&#xff0c;只保留输入输出接口&#x…...

python小游戏课程设计报告,python游戏课程设计报告

大家好&#xff0c;给大家分享一下python2048游戏课程设计报告&#xff0c;很多人还不知道这一点。下面详细解释一下。现在让我们来看看&#xff01;...

使用Windbg分析从系统应用程序日志中找到的系统自动生成的dump文件去排查问题

目录 1、尝试将Windbg附加到目标进程上进行动态调试&#xff0c;但Windbg并没有捕获到 2、在系统应用程序日志中找到了系统在程序发生异常时自动生成的dump文件 2.1、查看应用程序日志的入口 2.2、在应用程序日志中找到系统自动生成的dump文件 3、使用Windbg静态分析dump文…...

后端技术趋势指南|如何选择自己的技术方向

编程多条路&#xff0c;条条通罗马 后台大佬 后台路线都是面对后台服务器业务&#xff0c;比如web后台服务器&#xff0c;视频后台服务器&#xff0c;搜索后台服务器&#xff0c;游戏后台服务器&#xff0c;直播后台服务器&#xff0c;社交IM后台服务器等等&#xff0c;大部分…...

Delphi XE的原生JSONObject如何判断键值是否存在?

【问题现象】 Delphi XE的原生JSONObject&#xff0c;取出键值的时候如下&#xff1a; //json是传入的参数&#xff0c;里面包括"food_name"等之类的键值&#xff0c;没有food_type键值 procedure XXXXFunciton(json:TJSONObject) var strFoodName,strFoodType:S…...

Go Runtime功能初探

以下内容&#xff0c;是对 运行时 runtime的神奇用法[1] 的学习与记录 目录: 1.获取GOROOT环境变量 2.获取GO的版本号 3.获取本机CPU个数 4.设置最大可同时执行的最大CPU数 5.设置cup profile 记录的速录 6.查看cup profile 下一次堆栈跟踪数据 7.立即执行一次垃圾回收 8.给变量…...

Ubuntu系统下交叉编译openssl

一、参考资料 OpenSSL&&libcurl库的交叉编译 - hesetone - 博客园 二、准备工作 1. 编译环境 宿主机&#xff1a;Ubuntu 20.04.6 LTSHost&#xff1a;ARM32位交叉编译器&#xff1a;arm-linux-gnueabihf-gcc-11.1.0 2. 设置交叉编译工具链 在交叉编译之前&#x…...

树莓派超全系列教程文档--(62)使用rpicam-app通过网络流式传输视频

使用rpicam-app通过网络流式传输视频 使用 rpicam-app 通过网络流式传输视频UDPTCPRTSPlibavGStreamerRTPlibcamerasrc GStreamer 元素 文章来源&#xff1a; http://raspberry.dns8844.cn/documentation 原文网址 使用 rpicam-app 通过网络流式传输视频 本节介绍来自 rpica…...

23-Oracle 23 ai 区块链表(Blockchain Table)

小伙伴有没有在金融强合规的领域中遇见&#xff0c;必须要保持数据不可变&#xff0c;管理员都无法修改和留痕的要求。比如医疗的电子病历中&#xff0c;影像检查检验结果不可篡改行的&#xff0c;药品追溯过程中数据只可插入无法删除的特性需求&#xff1b;登录日志、修改日志…...

HTML 列表、表格、表单

1 列表标签 作用&#xff1a;布局内容排列整齐的区域 列表分类&#xff1a;无序列表、有序列表、定义列表。 例如&#xff1a; 1.1 无序列表 标签&#xff1a;ul 嵌套 li&#xff0c;ul是无序列表&#xff0c;li是列表条目。 注意事项&#xff1a; ul 标签里面只能包裹 li…...

376. Wiggle Subsequence

376. Wiggle Subsequence 代码 class Solution { public:int wiggleMaxLength(vector<int>& nums) {int n nums.size();int res 1;int prediff 0;int curdiff 0;for(int i 0;i < n-1;i){curdiff nums[i1] - nums[i];if( (prediff > 0 && curdif…...

Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器

第一章 引言&#xff1a;语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域&#xff0c;文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量&#xff0c;支撑着搜索引擎、推荐系统、…...

第25节 Node.js 断言测试

Node.js的assert模块主要用于编写程序的单元测试时使用&#xff0c;通过断言可以提早发现和排查出错误。 稳定性: 5 - 锁定 这个模块可用于应用的单元测试&#xff0c;通过 require(assert) 可以使用这个模块。 assert.fail(actual, expected, message, operator) 使用参数…...

论文解读:交大港大上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架(一)

宇树机器人多姿态起立控制强化学习框架论文解析 论文解读&#xff1a;交大&港大&上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架&#xff08;一&#xff09; 论文解读&#xff1a;交大&港大&上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化…...

ABAP设计模式之---“简单设计原则(Simple Design)”

“Simple Design”&#xff08;简单设计&#xff09;是软件开发中的一个重要理念&#xff0c;倡导以最简单的方式实现软件功能&#xff0c;以确保代码清晰易懂、易维护&#xff0c;并在项目需求变化时能够快速适应。 其核心目标是避免复杂和过度设计&#xff0c;遵循“让事情保…...

比较数据迁移后MySQL数据库和OceanBase数据仓库中的表

设计一个MySQL数据库和OceanBase数据仓库的表数据比较的详细程序流程,两张表是相同的结构,都有整型主键id字段,需要每次从数据库分批取得2000条数据,用于比较,比较操作的同时可以再取2000条数据,等上一次比较完成之后,开始比较,直到比较完所有的数据。比较操作需要比较…...