# Need help with Objective function

Hi,

I am new to CVX, and need to write the following objective function. Any help would be appreciated:

``````sum(N(:,j)'*R(:,:,j)*N(:,j))
``````

Where R is an n x n x m element. N is an n x n matrix. The sum is over j from 1 to m.

Apologies for not writing proper equations, I am still getting used to the forum software

Aman Gupta

Which one of these is a variable, and which is a constant? (They cannot both be variables.)

There’s no reason you can’t do something like this, assuming the intermediate quantities are legal:

``````obj = 0;
for j = 1 : size(R,3),
obj = obj + N(:,j)'*R(:,:,j)+N(:,j);
end
minimize(obj);``````

Thanks a lot for replying. N is a variable, while R is a constant. When I use the pseudo code written by you, I get the following error

The following cvx variable(s) have been cleared or overwritten: obj This is often an indication that an equality constraint was written with one equals '=' instead of two '=='. The model must be rewritten before cvx can proceed.

When I change the assignment operation to two equals operators, it works! This is a little awkward for me, because I am used to using ‘=’ for assignment and ‘==’ for equality checking. Am I doing things right?

1 Like

It sounds like you declared `obj` to be a variable. Don’t do that. If you declare it as an `expression` instead you would be fine.

2 Likes

(Though actually the easiest thing to do is not declare it at all.)

Thanks Michael, that worked!! 1 Like