# Using loop to minimize the average in the objective function

Dear all,

I am trying to solve the following optimization problem using “for loop”. The code can successfully run, but I am not sure the way I used “for loop” for deriving the sum is correct or not since the outcome seems a little bit wired.

I would appreciate it if anyone could help me. Thanks!

``````obj=0;
N=100;
cvx_begin
variable theta(6,2)
for i=1:N
obj=obj+quad_form( A' * theta' * x(:,i), Q )-z(:,i)' *A' * theta' * x(:,i) ;
end
minimize(obj2)
cvx_end
theta
``````

where A and Q are 2 by 2, x is 6 by 1 and z is 2 by 1 with N scenarios.

it looks o.k. to me, except that there is a typo as written, (`obj2` instead of `obj`) in the objective function. if you really ran it as written, then `obj2` is a constant, and therefore the problem is minimizing a constant, which is the same as a feasibility problem, and because it is unconstrained, that means the solver and CVX can return whatever value of `theta` they want, and will consider the problem to be solved.

You didn’t divide by `N`, but the optimal `theta `should not be affected by that unless there are some numerical issues.

if you show the CVX and solver output, together with the optimal value of `theta`, perhaps someone can say something more.

if you really did run it with `obj2`, CVX might not even bother calling the solver, and might “solve it” analytically, populating `theta` with all zeros (or perhaps something else).

Thanks for taking time! I typed the code here wrongly where cvx is minimizing obj instead of ojb2. Appreciate a lot!