0

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

slitvinov
  • 5,693
  • 20
  • 31
ADH
  • 13
  • 1
  • 3

2 Answers2

0

Since v may contain one or two elements only, add a test, for instance

if length(v)==1, 
   vertex = ... 
elseif length(v)==2
   vertex = ...
else
   vertex=(-v(2))/(2*v(3));
end

This should replace vertex=(-v(2))/(2*v(3));

Buck Thorn
  • 5,024
  • 2
  • 17
  • 27
  • along with all my other if elses :( – ADH Mar 03 '15 at 22:53
  • @ADH See my edit - you should leave the tail of your program (the test regarding the position of the vertex wrt a,b) alone – Buck Thorn Mar 03 '15 at 22:55
  • I see, but there are 2 cases when length(v)==2, when it's x^2 and an x term; or x^2 and a constant. Does this matter? – ADH Mar 03 '15 at 22:58
  • @ADH I don't know, that's a math problem but if there are different conditions just add another if/else subclause within the `length(v)==2` clause to address the two possibilities. Point is after this if/else tree you should come out with one value of vertex. – Buck Thorn Mar 03 '15 at 23:01
  • alright, a lot more if else's than I'd like and expect for this question, but I'll give it a go – ADH Mar 03 '15 at 23:04
0

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)));
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147