MATLAB: Defining simple optimization constraint: When x1 > 0 then x2 has to equal 0

MATLABmatrixoptimization

Hi there,
I'm working on an optimization problem with 2 decision variables x1 and x2. The problem optimizes the values of x1 and x2 each hour over a 24 hour period to minimize the objective function.
I've already defined 2 constraints as follows (using the code below):
Constraints:
0 <= x1 <= 3
0 <= x2 <= 3
N =24;
lb = zeros(2*N,1); % lower bound is 0
ub = 3*ones(2*N,1); % upper bound is 3
Now, I'm trying to define a constraint that says that only x1 or x2 can be greater than 0 at any one time. i.e. If x1 is greater than 0 then x2 has to equal 0 and vice versa. In the problem x1 and x2 refer to the energy flow in and out of a battery, therefore only one variable can be positive at a time.
if x1 > 0 then x2=0
or
if x2 > 0 then x1 = 0
I'm scratching my head but I can't seem to figure out how to define this constraint in matrix form.
I'd welcome any suggestions and thank you for your help.
Sincerely

Best Answer

This is a classical application of Dynamic Programming and that might be the most efficient way for you to go about this problem, see
One thing I don't understand, though, is why you have two separate variables, x1 and x2 for Energy_in and Energy_out? Can't you just have one decision variable x in each hourly period and treat x>0 as energy out and x<=0 as energy in? In other words, can't you just view Energy_out as positive energy consumption and Energy_in as negative energy consumption?