Create multi-dimensional variables, read data file in C++
AnsweredHi,
1. I would like to create several multi-dimensional decision variables in C++ using
const int I = 3;
const int J = 4;
const int K = 5;
GRBVar* v[I];
for (int i = 0; i < I; i++)
{
v[i] = model.addVars(J, GRB_BINARY);
}
GRBVar* v[I];
for (int i = 0; i < I; i++)
{
for (int j = 0; j < J; j++)
{
v[i] = model.addVars(K, GRB_BINARY);
}
}
May I ask if they are referring to binary variables v[i][j] and v[i][j][k]?
2. I need to read coefficients from a data file. I only found examples that define coefficients inside a cpp file, may I ask how to define these constants from a txt or dat file?
I just switch to C++ from AMPL recently, should I update my data file in a format like
[1]
[3,3]
[[0.9,0.5],
[0.4,0.8]]
or
1
3,3
0.9,0.5,0.4,0.8
if the coefficients are "b=1, c[1]=3, c[2]=3, d[1,1]=0.9, d[1,2]=0.5, d[2,1]=0.4 and d[2,2]=0.8?
Thank you in advance!
-
Hi,
Regarding your first question. The workforce1_c++.cpp example shows an application of a 2 dimensional variable object. For 3 dimensions, your code might look something like
#include "gurobi_c++.h"
#include <sstream>
using namespace std;
[...]
int I = 3;
int J = 4;
int K = 5;
GRBVar*** vars = 0;
[...]
vars = new GRBVar**[I];
for(int i = 0; i < I; i++){
vars[i] = new GRBVar*[J];
for(int j = 0; j < J; j++){
vars[i][j] = model.addVars(K);
for(int k = 0; k < K; k++){
ostringstream vname;
vname << "v[" << i << "," << j << "," << k << "]";
vars[i][j][k].set(GRB_CharAttr_VType, GRB_BINARY);
vars[i][j][k].set(GRB_StringAttr_VarName, vname.str());
}
}
}
for (int i = 0; i < I; i++){
GRBLinExpr lhs = 0;
for (int j = 0; j < J; j++){
for(int k = 0; k < K; k++){
lhs += vars[i][j][k];
}
}
model.addConstr(lhs == 1);
}
[...]
// Don't forget to delete
for (int i = 0; i < I; i++){
for (int j = 0; j < J; j++){
delete[] vars[i][j];
}
delete[] vars[i];
}
delete[] vars;Regarding your second question. There is a vast number of ways to read in data from a file in C++. One way is described in the stackoverflow post Read file line by line using ifstream in C++.
Best regards,
Jaromił0 -
Thank you so much for your help Jaromił! That helps me a lot!
Best,
Zeyu
0
Please sign in to leave a comment.
Comments
2 comments