# Expression holder and expression assignment must be before the obejctive?

Must expression holders and the expression assignment be done before the objective? It surprised me that the following gave different results:

``````cvx_begin
variable x
expression e
e = x
maximize(e)
x <= 1
x >= -1
cvx_end
>> Optimal value (cvx_optval): +1
``````

and

``````cvx_begin
variable x
expression e
maximize(e)
e = x
x <= 1
x >= -1
cvx_end
>> Optimal value (cvx_optval): +0
``````

Is there something I am missing why the results are not identical? Yes, this is expected. Don’t confuse assignment with equality… In fact you really don’t need to declare an expression holder if you simply want an alias for an expression. The expression statement creates an expression with the constant value zero until it is overwritten by an assignment.

Awesome makes sense - thanks! No problem. Truthfully, the `expression` keyword is less useful than I originally conceived it to be. The primary reason you might need it is if you need to create a vector of CVX expressions, element-by-element. For instance:

``````expression x(n)
for k = 1 : n
x(k) = <code here>
end
``````

If you tried to do this instead,

``````x = [] % or x = zeros(n,1)
for k = 1 : n
x(k) = <code here>
end
``````

You would get an error, because you’d be attempting to assigned a CVX expression to an element of a numeric vector. In this context, the `expression` keyword creates a CVX object that is ready to accept intermediate expressions. In fact, this would work too:

``````x = cvx(zeros(n,1))
for k = 1 : n
x(k) = <code here>
end
``````

But if you simply want to give a name to an intermediate calculation, such as `e = x` above, there’s really no need to pre-declare `e` to be an expression. Just do it!

1 Like