31.利用linprog 解决 投资问题(matlab程序)

1.简述

      

 

语法:[X,FVAL] = linprog(f,a,b,Aeq,Beq,LB,UB,X0);

    X 为最终解 , FVAL为最终解对应的函数值
    *注意:求最大值时,结果FVAL需要取反*
    
    f 为决策函数的系数矩阵。
    *注意:当所求为最大值时,系数矩阵需要取反*
    
    a 为约束条件中不等式组的系数矩阵 ,a的列数等于f的列数
    *注意:当不等号为  > 或  ≥ 时,矩阵需要取反*
    
    b 为约束条件中不等式组右边的值
    *注意:当不等号为  > 或  ≥ 时,矩阵需要取反*
    
    Aeq 为约束条件中等式组的系数矩阵 ,Aeq的列数等于f的列数
    
    Beq 为约束条件中等式组右边的值
    
    LB、UB 是解的范围
    
    X0  为初始值
 

2.代码

 

主程序:

%%   投资问题
f=[-0.2;-0.12;-0.09;-0.14];
A=[1,-1,-1,-1;0,-1,-1,1];
b=[0;0];
Aeq=[1,1,1,1];
beq=1;
l=[0 0 0];
u=[1 1 1];
[xo,yo,exitflag]=linprog(f,A,b,Aeq,beq,l,u)

 

 

子程序:

function [x,fval,exitflag,output,lambda]=linprog(f,A,B,Aeq,Beq,lb,ub,x0,options)
%LINPROG Linear programming.
%   X = LINPROG(f,A,b) attempts to solve the linear programming problem:
%
%            min f'*x    subject to:   A*x <= b
%             x
%
%   X = LINPROG(f,A,b,Aeq,beq) solves the problem above while additionally
%   satisfying the equality constraints Aeq*x = beq. (Set A=[] and B=[] if
%   no inequalities exist.)
%
%   X = LINPROG(f,A,b,Aeq,beq,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 = LINPROG(f,A,b,Aeq,beq,LB,UB,X0) sets the starting point to X0. This
%   option is only available with the active-set algorithm. The default
%   interior point algorithm will ignore any non-empty starting point.
%
%   X = LINPROG(PROBLEM) finds the minimum for PROBLEM. PROBLEM is a
%   structure with the vector 'f' in PROBLEM.f, the linear inequality
%   constraints in PROBLEM.Aineq and PROBLEM.bineq, the linear equality
%   constraints in PROBLEM.Aeq and PROBLEM.beq, the lower bounds in
%   PROBLEM.lb, the upper bounds in  PROBLEM.ub, the start point
%   in PROBLEM.x0, the options structure in PROBLEM.options, and solver
%   name 'linprog' in PROBLEM.solver. Use this syntax to solve at the
%   command line a problem exported from OPTIMTOOL.
%
%   [X,FVAL] = LINPROG(f,A,b) returns the value of the objective function
%   at X: FVAL = f'*X.
%
%   [X,FVAL,EXITFLAG] = LINPROG(f,A,b) returns an EXITFLAG that describes
%   the exit condition. Possible values of EXITFLAG and the corresponding
%   exit conditions are
%
%     3  LINPROG converged to a solution X with poor constraint feasibility.
%     1  LINPROG converged to a solution X.
%     0  Maximum number of iterations reached.
%    -2  No feasible point found.
%    -3  Problem is unbounded.
%    -4  NaN value encountered during execution of algorithm.
%    -5  Both primal and dual problems are infeasible.
%    -7  Magnitude of search direction became too small; no further
%         progress can be made. The problem is ill-posed or badly
%         conditioned.
%    -9  LINPROG lost feasibility probably due to ill-conditioned matrix.
%
%   [X,FVAL,EXITFLAG,OUTPUT] = LINPROG(f,A,b) returns a structure OUTPUT
%   with the number of iterations taken in OUTPUT.iterations, maximum of
%   constraint violations in OUTPUT.constrviolation, the type of
%   algorithm used in OUTPUT.algorithm, the number of conjugate gradient
%   iterations in OUTPUT.cgiterations (= 0, included for backward
%   compatibility), and the exit message in OUTPUT.message.
%
%   [X,FVAL,EXITFLAG,OUTPUT,LAMBDA] = LINPROG(f,A,b) returns the set of
%   Lagrangian multipliers LAMBDA, at the solution: LAMBDA.ineqlin for the
%   linear inequalities A, LAMBDA.eqlin for the linear equalities Aeq,
%   LAMBDA.lower for LB, and LAMBDA.upper for UB.
%
%   NOTE: the interior-point (the default) algorithm of LINPROG uses a
%         primal-dual method. Both the primal problem and the dual problem
%         must be feasible for convergence. Infeasibility messages of
%         either the primal or dual, or both, are given as appropriate. The
%         primal problem in standard form is
%              min f'*x such that A*x = b, x >= 0.
%         The dual problem is
%              max b'*y such that A'*y + s = f, s >= 0.
%
%   See also QUADPROG.

%   Copyright 1990-2018 The MathWorks, Inc.

% If just 'defaults' passed in, return the default options in X

% Default MaxIter, TolCon and TolFun is set to [] because its value depends
% on the algorithm.
defaultopt = struct( ...
    'Algorithm','dual-simplex', ...
    'Diagnostics','off', ...
    'Display','final', ...
    'LargeScale','on', ...
    'MaxIter',[], ...
    'MaxTime', Inf, ...
    'Preprocess','basic', ...
    'TolCon',[],...
    'TolFun',[]);

if nargin==1 && nargout <= 1 && strcmpi(f,'defaults')
   x = defaultopt;
   return
end

% Handle missing arguments
if nargin < 9
    options = [];
    % Check if x0 was omitted and options were passed instead
    if nargin == 8
        if isa(x0, 'struct') || isa(x0, 'optim.options.SolverOptions')
            options = x0;
            x0 = [];
        end
    else
        x0 = [];
        if nargin < 7
            ub = [];
            if nargin < 6
                lb = [];
                if nargin < 5
                    Beq = [];
                    if nargin < 4
                        Aeq = [];
                    end
                end
            end
        end
    end
end

% Detect problem structure input
problemInput = false;
if nargin == 1
    if isa(f,'struct')
        problemInput = true;
        [f,A,B,Aeq,Beq,lb,ub,x0,options] = separateOptimStruct(f);
    else % Single input and non-structure.
        error(message('optim:linprog:InputArg'));
    end
end

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

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

if nargin < 3 && ~problemInput
  error(message('optim:linprog:NotEnoughInputs'))
end

% Define algorithm strings
thisFcn  = 'linprog';
algIP    = 'interior-point-legacy';
algDSX   = 'dual-simplex';
algIP15b = 'interior-point';

% Check for non-double inputs
msg = isoptimargdbl(upper(thisFcn), {'f','A','b','Aeq','beq','LB','UB', 'X0'}, ...
                                      f,  A,  B,  Aeq,  Beq,  lb,  ub,   x0);
if ~isempty(msg)
    error('optim:linprog:NonDoubleInput',msg);
end

% After processing options for optionFeedback, etc., set options to default
% if no options were passed.
if allDefaultOpts
    % Options are all default
    options = defaultopt;
end

if nargout > 3
   computeConstrViolation = true;
   computeFirstOrderOpt = true;
   % Lagrange multipliers are needed to compute first-order optimality
   computeLambda = true;
else
   computeConstrViolation = false;
   computeFirstOrderOpt = false;
   computeLambda = false;
end

% Algorithm check:
% If Algorithm is empty, it is set to its default value.
algIsEmpty = ~isfield(options,'Algorithm') || isempty(options.Algorithm);
if ~algIsEmpty
    Algorithm = optimget(options,'Algorithm',defaultopt,'fast',allDefaultOpts);
    OUTPUT.algorithm = Algorithm;
    % Make sure the algorithm choice is valid
    if ~any(strcmp({algIP; algDSX; algIP15b},Algorithm))
        error(message('optim:linprog:InvalidAlgorithm'));
    end
else
    Algorithm = algDSX;
    OUTPUT.algorithm = Algorithm;
end

% Option LargeScale = 'off' is ignored
largescaleOn = strcmpi(optimget(options,'LargeScale',defaultopt,'fast',allDefaultOpts),'on');
if ~largescaleOn
    [linkTag, endLinkTag] = linkToAlgDefaultChangeCsh('linprog_warn_largescale');
    warning(message('optim:linprog:AlgOptsConflict', Algorithm, linkTag, endLinkTag));
end

% Options setup
diagnostics = strcmpi(optimget(options,'Diagnostics',defaultopt,'fast',allDefaultOpts),'on');
switch optimget(options,'Display',defaultopt,'fast',allDefaultOpts)
    case {'final','final-detailed'}
        verbosity = 1;
    case {'off','none'}
        verbosity = 0;
    case {'iter','iter-detailed'}
        verbosity = 2;
    case {'testing'}
        verbosity = 3;
    otherwise
        verbosity = 1;
end

% Set the constraints up: defaults and check size
[nineqcstr,nvarsineq] = size(A);
[neqcstr,nvarseq] = size(Aeq);
nvars = max([length(f),nvarsineq,nvarseq]); % In case A is empty

if nvars == 0
    % The problem is empty possibly due to some error in input.
    error(message('optim:linprog:EmptyProblem'));
end

if isempty(f), f=zeros(nvars,1); end
if isempty(A), A=zeros(0,nvars); end
if isempty(B), B=zeros(0,1); end
if isempty(Aeq), Aeq=zeros(0,nvars); end
if isempty(Beq), Beq=zeros(0,1); end

% Set to column vectors
f = f(:);
B = B(:);
Beq = Beq(:);

if ~isequal(length(B),nineqcstr)
    error(message('optim:linprog:SizeMismatchRowsOfA'));
elseif ~isequal(length(Beq),neqcstr)
    error(message('optim:linprog:SizeMismatchRowsOfAeq'));
elseif ~isequal(length(f),nvarsineq) && ~isempty(A)
    error(message('optim:linprog:SizeMismatchColsOfA'));
elseif ~isequal(length(f),nvarseq) && ~isempty(Aeq)
    error(message('optim:linprog:SizeMismatchColsOfAeq'));
end

[x0,lb,ub,msg] = checkbounds(x0,lb,ub,nvars);
if ~isempty(msg)
   exitflag = -2;
   x = x0; fval = []; lambda = [];
   output.iterations = 0;
   output.constrviolation = [];
   output.firstorderopt = [];
   output.algorithm = ''; % not known at this stage
   output.cgiterations = [];
   output.message = msg;
   if verbosity > 0
      disp(msg)
   end
   return
end

if diagnostics
   % Do diagnostics on information so far
   gradflag = []; hessflag = []; constflag = false; gradconstflag = false;
   non_eq=0;non_ineq=0; lin_eq=size(Aeq,1); lin_ineq=size(A,1); XOUT=ones(nvars,1);
   funfcn{1} = []; confcn{1}=[];
   diagnose('linprog',OUTPUT,gradflag,hessflag,constflag,gradconstflag,...
      XOUT,non_eq,non_ineq,lin_eq,lin_ineq,lb,ub,funfcn,confcn);
end

% Throw warning that x0 is ignored (true for all algorithms)
if ~isempty(x0) && verbosity > 0
    fprintf(getString(message('optim:linprog:IgnoreX0',Algorithm)));
end

if strcmpi(Algorithm,algIP)
    % Set the default values of TolFun and MaxIter for this algorithm
    defaultopt.TolFun = 1e-8;
    defaultopt.MaxIter = 85;
    [x,fval,lambda,exitflag,output] = lipsol(f,A,B,Aeq,Beq,lb,ub,options,defaultopt,computeLambda);
elseif strcmpi(Algorithm,algDSX) || strcmpi(Algorithm,algIP15b)

    % Create linprog options object
    algoptions = optimoptions('linprog', 'Algorithm', Algorithm);

    % Set some algorithm specific options
    if isfield(options, 'InternalOptions')
        algoptions = setInternalOptions(algoptions, options.InternalOptions);
    end

    thisMaxIter = optimget(options,'MaxIter',defaultopt,'fast',allDefaultOpts);
    if strcmpi(Algorithm,algIP15b)
        if ischar(thisMaxIter)
            error(message('optim:linprog:InvalidMaxIter'));
        end
    end
    if strcmpi(Algorithm,algDSX)
        algoptions.Preprocess = optimget(options,'Preprocess',defaultopt,'fast',allDefaultOpts);
        algoptions.MaxTime = optimget(options,'MaxTime',defaultopt,'fast',allDefaultOpts);
        if ischar(thisMaxIter) && ...
                ~strcmpi(thisMaxIter,'10*(numberofequalities+numberofinequalities+numberofvariables)')
            error(message('optim:linprog:InvalidMaxIter'));
        end
    end

    % Set options common to dual-simplex and interior-point-r2015b
    algoptions.Diagnostics = optimget(options,'Diagnostics',defaultopt,'fast',allDefaultOpts);
    algoptions.Display = optimget(options,'Display',defaultopt,'fast',allDefaultOpts);
    thisTolCon = optimget(options,'TolCon',defaultopt,'fast',allDefaultOpts);
    if ~isempty(thisTolCon)
        algoptions.TolCon = thisTolCon;
    end
    thisTolFun = optimget(options,'TolFun',defaultopt,'fast',allDefaultOpts);
    if ~isempty(thisTolFun)
        algoptions.TolFun = thisTolFun;
    end
    if ~isempty(thisMaxIter) && ~ischar(thisMaxIter)
        % At this point, thisMaxIter is either
        % * a double that we can set in the options object or
        % * the default string, which we do not have to set as algoptions
        % is constructed with MaxIter at its default value
        algoptions.MaxIter = thisMaxIter;
    end

    % Create a problem structure. Individually creating each field is quicker
    % than one call to struct
    problem.f = f;
    problem.Aineq = A;
    problem.bineq = B;
    problem.Aeq = Aeq;
    problem.beq = Beq;
    problem.lb = lb;
    problem.ub = ub;
    problem.options = algoptions;
    problem.solver = 'linprog';

    % Create the algorithm from the options.
    algorithm = createAlgorithm(problem.options);

    % Check that we can run the problem.
    try
        problem = checkRun(algorithm, problem, 'linprog');
    catch ME
        throw(ME);
    end

    % Run the algorithm
    [x, fval, exitflag, output, lambda] = run(algorithm, problem);

    % If exitflag is {NaN, <aString>}, this means an internal error has been
    % thrown. The internal exit code is held in exitflag{2}.
    if iscell(exitflag) && isnan(exitflag{1})
        handleInternalError(exitflag{2}, 'linprog');
    end

end

output.algorithm = Algorithm;

% Compute constraint violation when x is not empty (interior-point/simplex presolve
% can return empty x).
if computeConstrViolation && ~isempty(x)
    output.constrviolation = max([0; norm(Aeq*x-Beq, inf); (lb-x); (x-ub); (A*x-B)]);
else
    output.constrviolation = [];
end

% Compute first order optimality if needed. This information does not come
% from either qpsub, lipsol, or simplex.
if exitflag ~= -9 && computeFirstOrderOpt && ~isempty(lambda)
    output.firstorderopt = computeKKTErrorForQPLP([],f,A,B,Aeq,Beq,lb,ub,lambda,x);
else
    output.firstorderopt = [];
end

 

3.运行结果

 

3f6f4a1a59704025af50a448a130d13c.png

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/58591.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

SpringBoot实现数据库读写分离

SpringBoot实现数据库读写分离 参考博客https://blog.csdn.net/qq_31708899/article/details/121577253 实现原理&#xff1a;翻看AbstractRoutingDataSource源码我们可以看到其中的targetDataSource可以维护一组目标数据源(采用map数据结构)&#xff0c;并且做了路由key与目标…

LeetCode 26 题:删除有序数组的重复项

思路 在写这一个题时&#xff0c;我突然想到了Python中的 set&#xff08;&#xff09;函数可能会有大用处&#xff0c;便选择了用Python写。 set&#xff08;&#xff09;函数可以将列表转化为集合&#xff0c;集合会保证元素的单一性&#xff0c;所以会自动删去相同字符。 …

sqlserver命令插入另一个数据库的数据主键自增

1、数据情况 两个数据库字段是一致的&#xff0c;其中OBJECTID是主键字段&#xff0c;而且两个表都是从1自增排序 2、需求 现在需要将另一个数据库中的数据&#xff0c;通过sqlserver语句的方法&#xff0c;来插入数据&#xff0c;保持自增字段是自增的 解决方法 sqlserv…

基于边缘无线协同感知的低功耗物联网LPIOT技术:赋能智慧园区方案以及数字工厂领域

回到2000年左右&#xff0c;物联网的底层技术支撑还是“ZigBee”&#xff0c;虽然当时ZigBee的终端功耗指标其实也并不庞大&#xff0c;但是&#xff0c;“拓扑复杂导致工程实施难度大”、“网络规模小导致的整体效率低下”都成为限制其发展的主要因素。 LPWAN&#xff0c;新一…

推荐两款github敏感信息搜集工具(gsil、gshark)

推荐两款github敏感信息搜集工具&#xff08;gsil、gshark&#xff09; - 云社区 - 腾讯云 (tencent.com) github敏感信息泄露是很多企业时常忽视的一个问题&#xff0c;国外有一份研究报告显示&#xff0c;在超过24,000份的GitHub公开数据中&#xff0c;发现有数千个文件中可能…

ChatGPT已打破图灵测试,新的测试方法在路上

生信麻瓜的 ChatGPT 4.0 初体验 偷个懒&#xff0c;用ChatGPT 帮我写段生物信息代码 代码看不懂&#xff1f;ChatGPT 帮你解释&#xff0c;详细到爆&#xff01; 如果 ChatGPT 给出的的代码不太完善&#xff0c;如何请他一步步改好&#xff1f; 全球最佳的人工智能系统可以通过…

在windows配置redis的一些错误及解决方案

目录 Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException:用客户端Redis Desktop Manager一样的密码端口&#xff0c;是可以正常连接的&#xff0c;但是运行java程序之后使用接口请求就会报错 Unable to connect to Redis; nested e…

使用正则表达式 移除 HTML 标签后得到字符串

需求分析 后台返回的数据是 这样式的 需要讲html 标签替换 high_light_text: "<span stylecolor:red>OPPO</span> <span stylecolor:red>OPPO</span> 白色 01"使用正则表达式 function stripHTMLTags(htmlString) {return htmlString.rep…

【腾讯云Cloud Studio实战训练营】使用Cloud Studio迅捷开发一个3D家具个性化定制应用

目录 前言&#xff1a; 一、腾讯云 Cloud Studio介绍&#xff1a; 1、接近本地 IDE 的开发体验 2、多环境可选&#xff0c;或连接到云主机 3、随时分享预览效果 4、兼容 VSCode 插件 5、 AI代码助手 二、腾讯云Cloud Studio项目实践&#xff08;3D家具个性化定制应用&…

WPF中自定义Loading图

纯前端方式&#xff0c;通过动画实现Loading样式&#xff0c;如图所示 <Grid Width"35" Height"35" HorizontalAlignment"Center" VerticalAlignment"Center" Name"Loading"><Grid.Resources><DrawingBrus…

程序员之马上结束任务

计算机系的男同学追班里一女同学&#xff0c;结果此女总是躲躲闪闪。 男的看没戏&#xff0c;就另找了一个去追&#xff0c;结果这女的不满意了&#xff0c;质问这男的为啥抛弃她。 男的问&#xff1a;“请教一个电脑问题&#xff0c;如果你点击一个程序&#xff0c;总是提示…

[openCV]基于赛道追踪的智能车巡线方案V1

import cv2 as cv import os import numpy as npimport time# 遍历文件夹函数 def getFileList(dir, Filelist, extNone):"""获取文件夹及其子文件夹中文件列表输入 dir&#xff1a;文件夹根目录输入 ext: 扩展名返回&#xff1a; 文件路径列表""&quo…

ffmpeg.c源码与函数关系分析

介绍 FFmpeg 是一个可以处理音视频的软件&#xff0c;功能非常强大&#xff0c;主要包括&#xff0c;编解码转换&#xff0c;封装格式转换&#xff0c;滤镜特效。FFmpeg支持各种网络协议&#xff0c;支持 RTMP &#xff0c;RTSP&#xff0c;HLS 等高层协议的推拉流&#xff0c…

docker创建镜像并上传云端服务器

docker创建镜像并上传云端服务器 docker容器与镜像的关系1.基本镜像相关文件创建1.1 创建dockerfile文件1.2.创建do.sh文件1.3 创建upload_server_api.py文件1.4 创建upload_server_webui.py文件1.5 文件保存位置 2. 创建镜像操作2.1 创建镜像2.3 创建容器2.2 进入环境容器2.3 …

Jenkins工具系列 —— 启动 Jenkins 服务报错

错误显示 apt-get 安装 Jenkins 后&#xff0c;自动启动 Jenkins 服务报错。 排查原因 直接运行jenkins命令 发现具体报错log&#xff1a;Failed to start Jetty或Failed to bind to 0.0.0.0/0.0.0.0:8080或Address already in use 说明&#xff1a;这里提示的是8080端口号…

LNMP及论坛搭建(第一个访问,单节点)

LNMP&#xff1a;目前成熟的一个企业网站的应用模式之一&#xff0c;指的是一套协同工作的系统和相关软件 能够提供静态页面服务&#xff0c;也可以提供动态web服务&#xff0c;LNMP是缩写 L&#xff1a;指的是Linux操作系统。 N&#xff1a;指的是nginx&#xff0c;nginx提…

【Vue3项目实战】vue3项目基于el-menu封装左侧菜单栏组件

文章目录 概述一、先看效果1.1 静态效果1.2 动态效果 二、核心思路三、全量代码3.1 文件目录结构3.2 /sidebar/index.vue 中3.3 /sidebar/sidebarItem.vue 中3.4 路由表结构 四、代码讲解五、SVG组件六、系列文章友链1、[配置husky、stylelint、commitlint&#xff0c;实现git提…

HadoopWEB页面上传文件报错Couldn‘t upload the file course_info.txt

HadoopWEB页面上传文件报错Couldn’t upload the file course_info.txt 右键F2检查发现&#xff1a;文件上传PUT操作的IP地址是节点IP别名识别不到导致 解决方法&#xff1a;在WEB页面访问浏览器所在机器上面配置hosts映射地址(注意:配置的是浏览器访问的地址不是hadoop节点所在…

使用Golang实现一套流程可配置,适用于广告、推荐系统的业务性框架——组合应用

在《使用Golang实现一套流程可配置&#xff0c;适用于广告、推荐系统的业务性框架——简单应用》中&#xff0c;我们看到了各种组合Handler的组件&#xff0c;如HandlerGroup和Layer。这些组件下面的子模块又是不同组件&#xff0c;比如LayerCenter的子组件是Layer。如果此时我…

网络安全(黑客)自学的误区

一、自学网络安全学习的误区和陷阱 1.不要试图先成为一名程序员&#xff08;以编程为基础的学习&#xff09;再开始学习 我在之前的回答中&#xff0c;我都一再强调不要以编程为基础再开始学习网络安全&#xff0c;一般来说&#xff0c;学习编程不但学习周期长&#xff0c;而…