Skip to main content

Incompatible Dimensions?

Answered

Comments

4 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support.
  • Eli Towle
    • Gurobi Staff

    Operations between an object from the matrix-friendly interface (MVar, MLinExpr, MQuadExpr) and an object from the term-based modeling interface (Var, LinExpr, QuadExpr) are largely unsupported. In your example, \( \texttt{first} \) is an MLinExpr object and \( \texttt{yvar} \) is a Var object.

    One way to resolve the issue is to define \( \texttt{yvar} \) as an MVar by adding it to the model with Model.addMVar():

    yvar = model.addMVar(shape=(1,), name='y')

    Note that you can use MVar() to create an MVar object from a list of Var objects, and MVar.tolist() to create a list of Var objects from an MVar object. These conversions can be useful in situations like yours. For example, an alternative solution is as follows:

    lin = first + gp.MVar(yvar)
    0
  • Victor Miller
    • Gurobi-versary
    • Curious
    • First Comment

    Eli, Thanks for the answer.  As a related question, is there a convenient way to sum MVars along an axis (as in numpy)?

     

    0
  • Eli Towle
    • Gurobi Staff

    Unfortunately, there isn't currently a built-in way to sum an MVar along an axis. As a workaround, you could create a numpy array of Var objects by leveraging the MVar.tolist() method, then sum along an axis with ndarray.sum():

    >>> x = model.addMVar(shape=(3,3), name='x')
    >>> model.update()

    >>> xarr = np.array(x.tolist())
    >>> xarr.sum(axis=1)
    array([<gurobi.LinExpr: x[0] + x[1] + x[2]>,
           <gurobi.LinExpr: x[3] + x[4] + x[5]>,
           <gurobi.LinExpr: x[6] + x[7] + x[8]>], dtype=object)
    0

Post is closed for comments.