# How to create Gurobi model using a matrix? (C++ API)

I have been working on the Gurobi (C++ API) using its reference manual for some time. I did not see any description in the manual regarding how to create the Gurobi model using a matrix and iterate through it. For instance, I have a 50x50 matrix and would like to create a model using that. So far I have tried GRBModel::set() but it did not work out.

This answer is specific to Python API. You need to use numpy library to create matrices and leverage gurobipy library to create variables & constraints. Please refer to the following link for more details: https://www.gurobi.com/documentation/9.5/quickstart_mac/cs_example_matrix1_py.html

Similar features should be available in other languages as well.

Edit-1: Sample gurobi code in C++

#include <iostream>
#include <vector>
#include "gurobi_c++.h"

int main () {
int n1 = 50; //Initialise variable count
int n2 = 50;

//allocate memory
GRBVar **x = new GRBVar *[n1];
for (int i = 0; i < n1; i++) {
x[i] = new GRBVar[n2];
}

//Create GRB environment
GRBEnv *env = 0;
env = new GRBEnv();
GRBModel model = GRBModel(*env);

//Set model name
model.set(GRB_StringAttr_ModelName, "sampleModel");

//Create variables
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
//Create binary variable
x[i][j] = model.addVar(0.0, 1.0, 1.0, GRB_BINARY);
}
}
}

• This seems useful for Python (using numpy) but I work on C++ API, is there an example or similar method for it? I have edited question with using C++ API
– asdf
Commented Mar 14, 2022 at 13:16
• You may have to create 2-D array in C++ for 50x50 matrix of your requirement and also you can get more hints from the example on below link: gurobi.com/documentation/9.5/examples/facility_cpp_cpp.html Commented Mar 14, 2022 at 17:38
• I have checked the example but it is a bit complicated. Could you describe a bit more about it and edit the answer? I can approve the answer then
– asdf
Commented Mar 18, 2022 at 22:02
• Where should I place my Matrix A, b, and c so that It will solve the model using matrices? Does 'model.addVar(0.0, 1.0, 1.0, GRB_BINARY)' require me to enter all variables manually? My purpose is to give A, b, c matrixes, and then it will give me the solution of the LP/IP.
– asdf
Commented Mar 22, 2022 at 14:01
• I'm not sure of such feature in C++ API. Python gurobipy supports such way of providing A,b,c matrices. Commented Mar 22, 2022 at 17:24