Hey,
as I did not find any details about this exact case, here is my question: Is it possible to define a constraint in a function? Since my program is getting bigger, I aimed to implement functions which can be called to either define the constraint in multiple for-loops or use vectorization.
This is a minimal example of my problem
m = 16; n = 8;
A = randn(m,n);
b = randn(m,1);
x_ls = A \ b;
cvx_begin
cvx_solver mosek
variable x(n)
minimize( norm(A*x-b) )
subject to
constraint(x)
cvx_end
and the function i’m using in this case:
function constraint(x)
x >= [1; 2; 3; 4; 5; 6; 7; 8];
end
This is the error message I am getting from CVX.
Incorrect number or types of inputs or outputs for function 'newcnstr'.
Error in >= (line 21)
b = newcnstr( evalin( 'caller', 'cvx_problem', '[]' ), x, y, '>=' );
Error in constraint (line 4)
out = x >= [1; 2; 3; 4; 5; 6; 7; 8];
Error in test_cvx (line 17)
constraint(x)
Maybe you can have a function return a string specifying the constraint, then eval the string in your main program. Or eval(my_constraint_function(...)) .
Thanks. The main benefit in should be to get a more reusable and compact code. Since, the CVX code in the function will be quite complicated in the end, the eval(...) option would not be very useful.
I have been able to initialize a CVX expression out(n, 1) and manually set the entries of x in the function. Afterward, the function will return the expression, and it can be used to construct a constraint in the original script.
expression out(n, 1)
constraint(out, x, n) >= (1:n).';
function f_out = constraint(in, x, n)
for i = 1:n
in(i) = x(i)*i;
end
f_out = in;
end
to define a constraint like this
A = (1:n).'
x.*A >= A;
Are there any downsides to a procedure like this in CVX?