Home > Back-end >  How to use matlab to quickly judge whether a function is convex?
How to use matlab to quickly judge whether a function is convex?

Time:05-19

For example, FX = x ^ 2 sin (x) Just for curiosity, I don't want to use the CVX toolbox to do this.

CodePudding user response:

You can check this within some interval [a,b] by checking if the second derivative is nonnegative. For this you have to define a vector of x-values, find the numerical second derivative and check whether it is not too negative:

a = 0;
b = 1;
margin = 1e-5;
point_count = 100;
f=@(x) x.^2   sin(x);
x = linspace(a, b, point_count)
is_convex = all(diff(x, 2) > -margin);

Since this is a numerical test, you need to adjust the parameter to the properties of the function, that is if the function does wild things on a small scale we might not be able to pick it up. E.g. with the parameters above the test will falsely report the function f=@(x)sin(99.5*2*pi*x-3) as convex.

CodePudding user response:

clear
syms x real
syms f(x) d(x) d1(x)
f = x^2   sin(x)
d = diff(f,x,2)==0
d1 = diff(f,x,2)
expSolution = solve(d, x)
if size(expSolution,1) == 0
    if eval(subs(d1,x,0))>0 
        disp("condition 1");
    else
        disp("condition 2");
    end
else
    disp("condition 3")
end
  • Related