# How to solve custom convex functions

Hi,

I am new to CVX. So please excuse me if this question is very trivial.

I have a custom convex function L as defined below:

``````L(t) = 0        for t >= 1
L(t) = (1-t)^2  for |t| < 1
L(t) = -4t      for t <= -1
``````

I am using this L(t) in my main objective function f(x) [minimize f(x) over x]:

``````f(x) = {other standard convex functions of x} + L(x)
subject to {some constraints}
``````

My question is how do I declare L(t)?. I tried to define a new matlab function in L.m as follows:

``````function y = L(t)

y = zeros(length(t), 1);

for i = 1 : length(t)
if abs(t(i)) < 1
y(i,1) = (1 - t(i)) ^ 2;
elseif t(i) <= -1
y(i,1) = -4 * t(i);
end
end
end
``````

But I get error while trying to solve the following problem (this is a hypothetical problem, where I have remove lot of other code to simplify):

``````xpos = [ randi([1, 20], 1, 30); randi([71, 90], 1, 30) ]';
ypos = ones(30, 1);

xneg = [ randi([61, 80], 1, 30); randi([11, 30], 1, 30) ]';
yneg = ones(30, 1) * -1;

x = [xpos;xneg];
y = [ypos;yneg];

cvx_begin quiet
variable w(2)
variable b

minimize(0.5 * (w' * w) + sum(L(y.*(x*w + b))))
cvx_end
``````

Am I violating any DCP rules of CVX in declaring L(t)? If I am not allowed to iterate over the elements of cvx variable (t in L, in this case), how else can I solve this problem?

Any help/pointer would be very helpful for me…

Thanks,

Ram.

Yes, you’re violating the rules in your definition of `L(t)`. You can’t use variables in logical statements like `if/then` clauses. Functions must obey the same disciplined convex programming rules as any other constraint or objective.

Your function looks very similar to the `huber_pos` function, though. I cannot help but think you could make L out of an appropriate scaling and translation of that function.

As mcg suggests, you can express `L(t)` using `huber_pos`. Here’s the one-liner: `huber_pos(1-t,2)`.

Wonderful, Bien! Thanks for contributing.