以LP格式编写目标功能和约束



我正在使用cvxpy解决目标函数。变量是大矩阵。我想创建一个函数来编写目标函数和对文本文件的约束,然后将其用于其他求解器,例如cplex。做到这一点的一种方法是将每个变量显式写入字符串并将它们串联以创建目标函数。但是,我正在寻找替代方式,以使表达不会变得太大。例如,如果变量如下:

[ w11, w12
  w21,  w22 ]

然后表达式为W11 W12 W21 W22。我们可以想象,如果可变矩阵增长,则表达式也会增长。

有没有办法将变量初始化为LP格式的矩阵?

MATLAB代码编写用于在CPLEX求解器中使用的文本文件...可能是有帮助的,如果您有更好的东西

,您可以将其发布
clc;
clear all;
close all;
%fileID = fopen('test2_in.txt','wt');
filename = fullfile('"E:...','ex_1.txt'); 
 fileID = fopen('ex_1.txt','w+'); 

formatSpec = 'MAXIMIZE n Obj:';
fprintf(fileID,formatSpec);

obj_coeff = [0.12 0.15];
%-------------------------------------------------------------------------
% Writing Objective function for the problem
for ii = 1:length(obj_coeff) 
     if ii==length(obj_coeff)
        formatSpec = '(%d) X_%d';
    else
        formatSpec = ' (%d) X_%d +';
    end
    fprintf(fileID,formatSpec,obj_coeff(ii),ii);
end
formatSpec = 'nnSUBJECT TO n';
fprintf(fileID,formatSpec);
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
%writing constraints
temp = 1;
for jj = 1:length(obj_coeff) 
    if jj==length(obj_coeff)
        formatSpec = ' X_%d <= %dn r %d:';
        fprintf(fileID,formatSpec ,jj,temp+1);
        temp = temp+1;
    else
        formatSpec = ' X_%d +';
        fprintf(fileID,formatSpec,jj);
    end        
end
formatSpec = 'nn binaryn ';
fprintf(fileID,formatSpec);
for ii = 1:1:length(obj_coeff) 
    formatSpec = 'X_%d ';
    fprintf(fileID,formatSpec,ii); 
end
formatSpec = 'nnEND';
fprintf(fileID,formatSpec);
fclose(fileID);

最新更新