Problem to express a convex statement

Hello guys. I want to minimize the deviation from the desired value, of all diagonal elements of a matrix. To be clear i have a matrix A(5x5x3). For each third dimension i want to minimize the expression |aii-1|, thus i want all diagonal elements for each third dimension to be as closes as possible to 1. I thought to put the expression x(i)==trace(abs(A(:,:,i)-1) i=1,2,3 , in constraints and minimize sum(x), but i took an error. If i put directly to minimize trace(abs(A(:,:,1)-1) its ok but i cant do it for all i=1,2,3,… Is there any way to solve my problem?

I would appreciate any help!!

There must be some aspect of the problem you haven’t told us about, or else your problem is completely trivial. If you want to minimize deviations from 1, then all those diagonal elements should be 1. So what are your constraints, or the other portion of your objective function?

Show us your first formulation. As for the second approach, if you can’t figure out how to vectorize, you can build up the objective function as an expression using a for loop.

Objective = 0
for i=1:3
  Objective = Objective + <ith term>

Thank you very much for your reply! Of courses the diagonal elements must obey to some other constraints. Specifically are voltages so must obey to power flow equations. I didint know that i could use loop in objective function, so this is what i wanted, my problem was solved!!

ps: I had an issue when i made the constraint x==trace(abs(A(:,:,i)-1))… I was taking the error real affine==positive convex!!

I’m g;ad you solved your problem. But bad on me for not telling you that your expression was an illegal (per CVX’s Disciplined Convex Programming rules) nonlinear equality constraint. Indeed the right thing to do in such situations is to make the left-hand side an expression and use =, rather than declaring it as a CVX variable and using ==.