Why am I getting "Your objective function is not a scalar" error?

This is my code:

load(‘C’)
r=C(:,4);
t=C(:,5);

n = size(C,1);
N = 100;

for i=1:n
eta(i,1) = randn()/2;
end

cvx_begin
variable x

maximize r’*x - t’*x

subject to

  ones(n,1)'*x == N

  x >= zeros(n,1)

  exp(-x/N) >= eta

cvx_end

The objective function should clearly be scalar. But it gives the error, “Your objective function is not a scalar”. What am I doing wrong?

Furthermore, if I write the last constraint as follows:

    for i=1:n
		exp(-x(i,1)/N) >= eta(i,1)
	end

then I get the following error: “Index exceeds matrix dimensions.”

You have declared the variable x to be a scalar, because you didn’t explicitly specify dimensions in the variable statement. Therefore your objective function winds up being a 1 by n vector, and the index for x is exceeded in the for loop version of your constraints.

I believe you want
variable x(n,1)

Oh, silly me!

Ok, now after doing the correction you suggested, it gives the following error in the objective function line: “Inner matrix dimensions must agree.” Why is that occurring now?

It looks like both terms of the objective function should be (1 by n) times (n by 1), which is a scalar. So show your whole program and do a whos just before the objective function. That should show the dimensions on everything including the CVX variable(s). Make sure you didn’t mix up n and N.

This is what I get when I do a whos:

Name              Size              Bytes  Class      Attributes

  N                 1x1                 8  double               
  C                34x5              1360  double               
  cvx_problem       1x1               544  cvxprob              
  eta              34x1               272  double               
  i                 1x1                 8  double               
  n                 1x1                 8  double               
  r                34x1               272  double               
  t                34x1               272  double               
  x                34x1              2089  cvx  

So, it seems the dimensions should be alright. Can’t figure out why this particular error is showing up.

Put parentheses around your objective function, which seems to somertimes be needed.
maximize(r'*x-t'*x)

I always use parentheses, as shown in the CVX Users’ Guide. But I believe you can get away with not using them in certain circumstances. I will have to defer to @mcg to make a more definitive statement.

Gee, thanks Mark! That worked! Good to learn about this best practice.