# Gurobi c++: Getting constraint matrix

I'm trying to get the constraint matrix from a Gurobi model in C++. In Python, one can get this by simply calling a method that will populate a scipy object (see this post). However, in a C++ fashion, one may expect three vectors (column, row, value) for the non-zero elements in the matrix.

One could technically iterate through the result of

GRBConstr* getConstrs() const;


however, I am not sure how efficient this method would be. Has anyone tried and found an efficient way of doing so?

EDIT:

One can also get the non-zero coefficients for a given variable with

GRBColumn getCol(GRBVar v)


EDIT 2: The first (possibly inefficient) idea is the following. Assume the object presolved stores the presolved model.

 auto         vars = presolved.getVars();
//Getting the vars and iterating through them
for (int v = 0; v < nVariables; ++v) {
//Get the column of the v-th var
auto varCol = presolved.getCol(vars[v]);

if (varCol.size() > 0) {
//For any constraint in the number of constraints of the presolved model
for (int c = 0; c < nconstr; ++c) {
auto val = varCol.getCoeff(c);
if (val > 1e-6 || val < -1e-6)
// Fill the matrix A with the value
A.at(c, v) = val;
}
}


}

• If you have a large problem, you probably want to avoid dense matrices (I'm guessing A in A.at[c, v] is stored as a dense array). If you choose to work with a sparse matrix, I would expect the following to be decent: get the total number of non-zero coeffs, then populate a sparse column-wise matrix by iterating over the columns of the model. – mtanneau Apr 13 at 1:04
• @mtanneau Yes, that would be the idea. I also missed to say that the column should already haveonly non-zero coefficients. If that is true, the solution works. And no, not necessarily A is dense, but as of my example, the loop is iterating over every (possibly zero) value – gdragotto Apr 13 at 13:19