Python中Gurobi矩阵变量约束索引的维度兼容问题求助
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 wroteBu=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 valuesMisplaced
s1variable definition
You're definings1 = 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 reshapes1[:,k]to a 3×1 column vector to match the LHS dimension. Additionally, ensure that all matrix multiplications result in compatible shapes:dDeltais a 4×4 diagonal matrix (fromdeltaBut, a 4×1 array)Bu@dDeltagives a 3×4 matrix, which when multiplied byuseq[i-k-2](4×1) gives a 3×1 vectorTs*np.linalg.inv(M)@(Bu@dDelta@useq[i-k-2])will correctly be a 3×1 vector
Missing parentheses in
m.optimize()
You havem.optimizeinstead ofm.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
deltaButis created: usingm.addMVar((4,1))is cleaner than creating four individual variables and combining them into an array. - Ensured
posanduare initialized as column vectors (3x1 and 4x1) to avoid unintended 1D array behavior during matrix multiplication. - Added
gp.GRB.MINIMIZEto the objective for clarity (Gurobi defaults to minimization, but it's good practice to specify).
内容的提问来源于stack exchange,提问作者waseem Khan

