Need help looking for local minimum on a parabola

2 views (last 30 days)
I was wondering if anyone would be able to help me out with this.. I need to use a function M file to determine the local minimum of a parabola where the critical points can also qualify as a minimum. Here is my code. Currently it is returning values without error but the values don't match any of my test data given by my instructor.
if true
function c = myminimum(f, a, b)
syms x v w;
w=solve(diff(f(x)));
v=subs(f(x), w);
if (a<v && a<b);
c=a;
elseif (b<v && b<a);
c=b;
else c=v;
end
end
Here is the test data if that helps:
if truea = myminimum(@(x) x^2+1,-3,2)
a = 1
a = myminimum(@(x) x^2+6*x-3,-2,0)
a = -11
a = myminimum(@(x) -2*x^2+10*x,3,8)
a = -48
a = myminimum(@(x) -x^2+2*x+1,5,6)
a = -23

Accepted Answer

Star Strider
Star Strider on 12 Oct 2014
Do you have to use the if block?
The easy way is to use the min function:
syms x v w;
w=solve(diff(f(x)));
z = [w a b];
v=subs(f(x), z);
[q,k] = min(v);
c = v(k);
If you must use the if loop:
syms x v w;
w=solve(diff(f(x)));
z = [w a b];
v=subs(f(x), z);
if (v(1)<v(2) && v(1)<v(3));
c=v(1);
elseif (v(2)<v(3));
c=v(2);
else
c=v(3);
end
If it makes you feel any better, the ‘correct’ answer to this set:
a = myminimum(@(x) x^2+6*x-3,-2,0)
a = -11
is in error. The correct answer is -12, corresponding to the minimum of the parabola.
  8 Comments
Dan
Dan on 16 Oct 2014
I'm having trouble with this same problem and tried using both the min function code and the if loop code you wrote, Star Strider, but I keep getting errors and I don't know how to fix them.
These are the errors I get from the code with the if loop: Error using sym/subsindex (line 663) Invalid indexing or function definition. When defining a function, ensure that the body of the function is a SYM object. When indexing, the input must be numeric, logical or ':'.
Error in sym>privformat (line 1473) x = subsindex(x)+1;
Error in sym/subsref (line 685) [inds{k},refs{k}] = privformat(inds{k});
Error in myminimum (line 3) w=solve(diff(f(x)));

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!