Variable is the CVXPY constructor for creating decision variables that an optimization problem can choose. Its argument specifies the variable’s dimension or shape. section 10.1.3
Choose a declaration that matches the optimization model:
- Use cp.Variable(1) for a single scalar decision variable. section 10.1.3
- Use cp.Variable(2) for a two-dimensional variable, or declare separate one-dimensional variables such as x1 and x2. section 10.1.3
- In portfolio rebalancing, define separate buy, sell, and tax-lot variables; derived positions are expressions formed from starting holdings and trades. section 13.3.1
A constrained scalar variable
The model declares x = cp.Variable(1), minimizes x² − 6x + 10, and constrains x to [4, 10]. After prob.solve(), x.value returns the optimal variable value, 4.0. section 10.1.3
Listing 10.1 A simple problem in cvxpy
import cvxpy as cp x = cp.Variable(1) objective = cp.Minimize(x ** 2 - 6 * x + 10) constraints = [x >= 4, x <= 10] prob = cp.Problem(objective, constraints) result = prob.solve() x.value
Inspect the complete CVXPY construction from variable declaration through objective, constraints, problem creation, solving, and value retrieval. section 10.1.3
