0

I'm a beginner at python and I try to use cvxpy library for my optimization project. I try to change the first value of my n dimensional variable But I get an AttributeError

import cvxpy as cp
S = cp.Variable(100)
S[0].value=320000

output:AttributeError: can't set attribute

It works for 1-dim variable

import cvxpy as cp
S = cp.Variable()
S.value=320000

Thanks in advance

  • What are you trying to achieve? *Fixing* a variable? Add a constraint to do this (or more ugly: use variable-bounds). I don't think you are allowed to touch a variables *value*. Depending on the use-case, there is also the concept of [Parameters](https://www.cvxpy.org/tutorial/intro/index.html#parameters). – sascha Jun 10 '20 at 10:20
  • So the S parameter is changing over time in my study and it is in one my constraints, I put this S in a for loop and set the lower and upper bounds for it, and I minimize another variable also depends on S. What I want to do is to set the first value of the S variable in advance, like S[0]=320000 but the others like S[1],...S[99] can take any value in optimization problem. I can edit the value of variable if it has 1-dim as I showed, but when it comes to multidimensional ones, It does not work – durmuş can Jun 10 '20 at 12:13
  • Either use parameters (if that works out nicely -> e.g. when it's always the same index in S -> split in param of size 1 and var of size n-1; it also safes multiple dcp-canonicalization) or a constraint for fixing (then you pay for dcp-canonicalization each time). Imho, don't touch `.value` except for reading out results (until you find some explicit documentation allowing this). Also: don't be misguided by the fact, that your code does not crash when using a singleton-var. Either this is a specialization (hidden param-usage), something not safeguarded with problems or...Imho: don't exploit it – sascha Jun 10 '20 at 12:25

1 Answers1

1

The 'Variable' object does not support item assignment. You may enforce your requirement as a constraint:

import cvxpy as cp
S = cp.Variable(100) # Define your variables

objective = ... # Define your objective function

constraints = [] # Create an array of constraints
constraints.append(S[0]==320000) # Make your requirement a constraint

# Add more constraints

prob = Problem(objective, constraints) # Define your optimization problem
prob.solve(verbose=True) # Solve the problem

print(S.value)

NandyGirl
  • 33
  • 4