Search code examples
rlinear-programminglpsolve

lpsolve API in R: Edit column


I'm using lpsolveAPI in R and would like to set coefficients for specified columns and rows (coefficient for specified constraint number and decision variable number).

However, whereas I can add new column (new decision variable) or set existing column, I can't edit the column as that option will remove all previous coefficients in that column.

For example, let it be 5 constraints and 2 decision variables. Then:

lps.model <- make.lp(5, 2) #create lp model
#set coefficients for the first 3 constraint for both variables
for (i in seq(1,2)) set.column(lps.model, i, c(1,2,3), indices = c(1,2,3)) 

The model looks like this:

Model name: 
            C1    C2    C3    C4         
Minimize     0     0     0     0         
R1           1     1     0     0  free  0
R2           2     2     0     0  free  0
R3           3     3     0     0  free  0
R4           0     0     0     0  free  0
R5           0     0     0     0  free  0
Kind       Std   Std   Std   Std         
Type      Real  Real  Real  Real         
Upper      Inf   Inf   Inf   Inf         
Lower        0     0     0     0  

Now I want to add coefficients for 4th and 5th constraints.

for (i in seq(1,2)) set.column(lps.model, i, c(4,5), indices = c(4,5))

The code will rewrite the model since set.column functions sets all coefficients that were not listed within the function parameters to 0.

Model name: 
            C1    C2         
Minimize     0     0         
R1           0     0  free  0
R2           0     0  free  0
R3           0     0  free  0
R4           4     4  free  0
R5           5     5  free  0
Kind       Std   Std         
Type      Real  Real         
Upper      Inf   Inf         
Lower        0     0 

I have a big matrix of constraints and decision variables and need to run alike loops for different sets of variables. Is there any way to edit existing columns without rewriting them?


Solution

  • You could use set.mat for this to set values in your A matrix one at a time. See the help here.

    For example:

    > set.mat(lps.model, 4,5,3)
    

    Will make the value of 4th row, 5th column to be 3, without overwriting anything else. So you can call set.mat within a double loop and change individual values.

    However, it would be much more efficient if you can create whole columns at a time (preprocessing to create the list of coefficients) and then adding them to the lps.model in one shot using set.column especially since you say you have a large matrix of decision variables.