You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Gurobi矩阵变量约束索引的维度兼容问题求助

Fixing Dimension Compatibility Issues in Gurobi Matrix Variable Constraints

Let's walk through the key issues in your code that are causing the dimension mismatch, and fix them step by step:

  • Incorrect initialization of Bu
    You wrote Bu=np.array((3,4)), which creates a 1D array with two elements [3,4], not a 3×4 matrix as you intended. You need to initialize it as a proper 3-row, 4-column matrix. For example:

    Bu = np.random.rand(3,4)  # Replace with your actual values
    
  • Misplaced s1 variable definition
    You're defining s1 = m.addMVar((3,N)) inside the second loop (for i in range(N+1,7)), which means you're creating a new 3×5 variable matrix every iteration. This is unnecessary and can cause confusion with variable scoping. Move this line outside the loop so it's created once.

  • Dimension mismatch in constraint expressions
    The left-hand side (LHS) of your constraint is a 3×1 numpy array, while the right-hand side (RHS) has a 1D MVar slice (s1[:,k]). Gurobi's MVar slices return 1D objects by default, so we need to reshape s1[:,k] to a 3×1 column vector to match the LHS dimension. Additionally, ensure that all matrix multiplications result in compatible shapes:

    • dDelta is a 4×4 diagonal matrix (from deltaBut, a 4×1 array)
    • Bu@dDelta gives a 3×4 matrix, which when multiplied by useq[i-k-2] (4×1) gives a 3×1 vector
    • Ts*np.linalg.inv(M)@(Bu@dDelta@useq[i-k-2]) will correctly be a 3×1 vector
  • Missing parentheses in m.optimize()
    You have m.optimize instead of m.optimize() — this won't actually run the optimization.


Fixed Full Code

import gurobipy as gp
import numpy as np

N = 5
m = gp.Model("matrix")
Ts = 0.2
M = np.eye(3)
D = np.eye(3)
C = np.eye(3)
# Fix: Initialize Bu as a proper 3x4 matrix
Bu = np.random.rand(3,4)  # Replace with your actual values
pos = np.array([0,0,0]).reshape(3,1)  # Ensure it's a column vector (3x1)
u = np.array([0,0,0,0]).reshape(4,1)  # Ensure it's a column vector (4x1)
xseq = []
xseq.append(pos)
useq = []

# 1st loop: Populate initial sequences
for i in range(1, N+1):
    xseq.append(pos)
    useq.append(u)

# Fix: Define s1 once outside the loop
s1 = m.addMVar((3, N))  # 3x5 matrix variable
obj1 = 0

# 2nd loop
for i in range(N+1, 7):
    A = np.eye(3)
    # Create deltaBut variables as a 4x1 MVar instead of individual vars (cleaner)
    deltaBut = m.addMVar((4,1))
    dDelta = np.diag(deltaBut.flatten())  # Convert to 4x4 diagonal matrix
    
    for k in range(0, N):
        # Calculate RHS components with correct dimensions
        rhs_part = Ts * np.linalg.inv(M) @ Bu @ dDelta @ useq[i-k-2]
        # Reshape s1[:,k] to 3x1 to match LHS dimension
        m.addConstr(xseq[i-k-1] - A @ xseq[i-k-2] == rhs_part + s1[:,k].reshape(3,1))
        # Update objective with quadratic term
        obj1 += s1[:,k] @ s1[:,k]

# Set objective and optimize
m.setObjective(10**3 * obj1, gp.GRB.MINIMIZE)  # Specify minimization (optional but clear)
m.optimize()

Additional Notes

  • I changed how deltaBut is created: using m.addMVar((4,1)) is cleaner than creating four individual variables and combining them into an array.
  • Ensured pos and u are initialized as column vectors (3x1 and 4x1) to avoid unintended 1D array behavior during matrix multiplication.
  • Added gp.GRB.MINIMIZE to the objective for clarity (Gurobi defaults to minimization, but it's good practice to specify).

内容的提问来源于stack exchange,提问作者waseem Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:57:42