matlabfunctionif-statementminima

Matlab Maxima Minima Function


So I'm a couple of steps away from successfully writing this function:

enter image description here

Here is what I have so far:

function a=myanalyzecp(f,a,b)
syms x;
v=coeffs(f(x)); % grabs function's coefficients
vertex=(-v(2))/(2*v(3)); % vertex formula 
if (a<vertex && vertex<b)
    if (diff(diff(f(x)))>0) % f''>0 means minima
        a=1;
    else
        a=-1;
    end
else
    a=0;
end

The problem I'm running into is when the function only has 1 or 2 terms, such as x^2 or x^2+4 or x^2+4*x. Because then my vertex function fails


Solution

  • To obtain all coefficients including zeros, use sym2poly instead of coeffs:

    v = sym2poly(f(x));
    

    That gives the result as a double vector, not as a sym. If you need it to be a sym you need to convert:

    v = sym(sym2poly(f(x)));