Plotting and maximizing a function subject to constraints (using an anonymous function)?
2 views (last 30 days)
Show older comments
I have a function f(x) = -(x-alpha)^2 and I want to maximize it subject to the constraints x >= 0 and x<= 4. Let's say for starters the value of alpha = 5.
I want to graph the function f(x) and vertical lines marking the lower and upper boundaries of the constraints (so basically a line at x = 0 and x =4) and then a dot at the point where the function is maximized, subject to those constraints.
I am trying to define an anonymous function f = @(x) - 4 (x - alpha)^.2 after setting the value of alpha, so that I can then use if statements to calculate the constrained maximum and then plot everything... I need help! Thanks!
0 Comments
Answers (1)
Star Strider
on 14 Sep 2015
Edited: Star Strider
on 14 Sep 2015
The easy way:
f = @(x) - 4 .* (x(1) - x(2)).^2;
x = fmincon(@(x)-f(x), [2; 5], [], [], [], [], [0; -Inf], [4; Inf])
x =
2.0075
2.0075
Here, x(1) is ‘x’, and x(2) is ‘alpha’. The solutions are not unique, as you can easily demonstrate with different initial parameter estimates. (I suspect this is a ‘proxy’ Question for a different problem.)
2 Comments
Star Strider
on 14 Sep 2015
My plesure!
The plot is easier than the fmincon call:
f = @(x) - 4 .* (x(1) - x(2)).^2;
x = fmincon(@(x)-f(x), [1; 5], [], [], [], [], [0; -Inf], [4; Inf])
xlims = [0, 4];
figure(1)
plot(x(1), x(2), 'bp')
hold on
plot(xlims(1)*[1, 1], ylim, 'r-', xlims(2)*[1, 1], ylim,'r-', 'LineWidth',2)
hold off
grid
axis([-1 5 ylim])
That should do what you want.
See Also
Categories
Find more on 2-D and 3-D Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!