 # How to write an if loop inside cvx code?

Hello everyone,

In order to solve my optimization problem, I need to use an exponential function. As this function cannot be solve with cvx, I linearized this function. My problem is that I linearized this function using different segments. Therefore, depending on the value of the variable, I have to use one of the linearized functions. I tried to do this building a function with piecewise, but this is not working with cvx. So I want to do it using an if loop. However, when I tried this method this error appears:

“The following error occurred converting from cvxcnst to logical:
Disciplined convex programming error:
Constraints may not appear in if/then statements”

Does anyone know how to solve this problem? Thank you in advanced.

I give here an code example of what I want to do:

if 60 <= theta_hst < 90
V == 2.5theta_hst+ 4;
elseif 90 <= theta_hst < 120
V == 4.5
theta_hst+ 5;
else
V == 6.5*theta_hst+ 6;
end

Where theta_hst is the variable I want to optimize.

You will have to do logic modeling using Big M. Search on this forum for some references if you need them.

But are you sure you need piecewise functions? CVX does have an ability to deal with exponential functions, under certain limitations.

help cvx/exp

``````Disciplined convex programming information:
exp(X) is convex and nondecreasing in X. When used in CVX
expressions, X must be real. Typically, X must also be affine
or convex; X can also be concave, but this produces a log-concave
result with very limited usefulness.

Disciplined geometric programming information:
exp(X) is typically not used in geometric programs. However,
exp(X), where X is a monomial or posynomial, can be included in
geometric programs wherever a posynomial would be appropriate.``````