# How to minimize/maximize a sum calculated by for-loop?

``````x=[
-1.10	-0.55
0.40	-0.82
-0.96	1.11
0.17	-0.61
-1.97	-0.25
-0.74	-0.27
]
y=[2, 2, 2]

A = full(A);
sum=0;
cvx_begin
variable A(3,6)
minimize(sum)
subject to
for i=1:2
Ax=A*x(:,i);
sum=sum-Ax(y(i))+log(exp(Ax(1))+exp(Ax(2))+exp(Ax(3)));
end
sum=sum+3*norm(A,1);
cvx_end
``````

I have no idea how to minimize the “sum” here, the result seems to take the sum=0 which is defined before cvx operation…

As you have it, sum in the objective is the constant 0, so it is equivalent to not having an objective function.

Move `sum =0` to after cvc_begin, and get rid of
`subject to`
and move everything between that and cvx_end to before minimize.

I am not sure what you want to do with A. Is that what you are trying to optimize with respect to? if so, get rid of A = full(A) . That is overridden when A is declared a variable in CVX. I don;t know what you want to do with y, but it is not used in your CVX program.

You should use log_sum_exp.

If you do all of this, you might still not have the program you want. I suggest you re-read the CVX Users’ Guide and pay attention to the examples.

Thank you! It actually worked, and it also seems that the existence of “subject to” doesn’t matter here

As stated in the CVX USers’ Guide

The subject to statement does nothing—CVX provides this statement simply to make specifications
more readable. As with indentation, it is optional.

I never use it. But for people who do, you can use it if you want. If you have no constraints, and you did not, `subject to` still does nothing, but might be confusing to someone looking at it - that is why I told you to get rid of it. But yes, you can keep it if you want. You can even have a bunch of them.

Thanks again for the explanation!