Originally posted by: SystemAdmin
Using an IloExpr::LinearIterator you can iterate over the non-zero terms of an IloRange:
IloExpr expr = range.getExpr();
for (IloExpr::LinearIterator l = expr.getLinearIterator(); l.ok(); ++l)
{ std::cout << l.getCoef() <<
" * " << l.getVar() << std::endl;
}
Since you also need the zero entries an probably also a particular order of the variables you need to do more. Assuming you have all your variables in an IloNumArray x you could store the non-zero coefficients in a map and then do something like this (untested code)
// Compare instances of IloNumVar by their extractable id. struct LessIloNumVar
{ bool operator()(IloNumVar const& v1, IloNumVar const& v2)
const
{
return v1.getId() < v2.getId();
}
};
// Iterate over expression and store non-zero coefficients in a map. typedef std::map<IloNumVar,IloNum,LessIloNumVar> VarMap; VarMap varmap; IloExpr expr = range.getExpr();
for (IloExpr::LinearIterator l = expr.getLinearIterator(); l.ok(); ++l)
{
// If the variable is already in the map then we just update the
// coefficient. Otherwise we insert the variable into the map. VarMap::iterator it = varmap.find(l.getVar());
if ( it == varmap.end() ) varmap.insert(VarMap::value_type(l.getVar(), l.getCoef()));
else it->second += l.getCoef();
}
// Iterate over all variables and fetch their coefficients from the map.
// If a variable is not in the map then its coefficient is 0. IloNumArray vec(x.getEnv());
for (IloInt i = 0; i < x.getSize(); ++i)
{ VarMap::const_iterator it = varmap.find(x[i]); vec.add(it == varmap.end() ? 0 : it->second);
}
// vec is now the vector you are looking for.
#CPLEXOptimizers#DecisionOptimization