Model.addMVar (“addMVar”) in the Gurobi Python API creates multiple decision variables at once. It is the counterpart to addVar, which adds only a single variable. For high-dimensional models, addMVar makes the code shorter, clearer, and less error-prone, since you do not need to loop over large collections of variables.
Compared to addVar, the key distinction is that addMVar can add an entire array of variables in a single call. This reduces Python overhead and makes it easier to organize variables in models that naturally involve vectors or matrices, such as portfolio optimization, scheduling, or network flow problems.
The central argument is shape, which defines the size of the variable array. Bounds can be set through lb and ub, either as scalars or arrays of the same shape. The type of variable is specified with vtype (continuous, binary, or integer). A name string can also be provided, which Gurobi will use as a base for naming each variable. Ensuring that bounds or type arrays match the chosen shape is essential.
addMVar speeds up model construction in Python by replacing many repeated calls to addVar with a single call. This reduces overhead and keeps model code cleaner and more scalable. It does not, however, change the underlying solver runtime.
The method returns a gurobipy.MVar object, which is designed to behave like a NumPy array of variables. You can index into it, slice it, and iterate through it just like an array, which makes it straightforward to build constraints or objectives involving subsets of variables.
The method returns a tuple-like object that behaves similarly to an array of Gurobi variables. You can index and iterate through it, assign values, or use slices to apply constraints to subsets of variables. Understanding the structure of this output is key to writing clear and efficient code.
Yes, and in fact, it’s common practice. You can use NumPy arrays to define the bounds, objective coefficients, or even constraints, making your optimization model more compact and computationally efficient.
Common pitfalls include mismatched array dimensions, incorrect bounds, or improper variable types. Always validate your input arrays and check the Gurobi model for updates. Use the built-in model diagnostics to identify and fix issues quickly.
The Gurobi Jupyter Notebook Repository includes Python notebooks that demonstrate the use of Gurobi addMVar across various problem types. These include supply chain optimization, scheduling, and portfolio selection.
Yes, once variables are added, you can update their attributes using methods like .setAttr() or by modifying their values directly. This is useful for iterative modeling or when adapting models to changing business requirements.
Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.
Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.