1+ classdef QuadraticPolynomial
2+ properties
3+ A ,B ,C % Coefficients of a*x^2 + b*x + c
4+ end
5+
6+ methods
7+ function obj = QuadraticPolynomial(a ,b ,c )
8+ if ~isa(a ," numeric" ) || ~isa(b ," numeric" ) || ~isa(c ," numeric" )
9+ error(" QuadraticPolynomial:InputMustBeNumeric" , ...
10+ " Coefficients must be numeric." )
11+ else
12+ obj.A = a ; obj.B = b ; obj.C = c ;
13+ end
14+ end
15+
16+ function r = solve(obj )
17+ % Return solutions to a*x^2 + b*x + c = 0
18+ delta = calculateDelta(obj );
19+ r(1 ) = (-obj .B - sqrt(delta )) / (2 * obj .A);
20+ r(2 ) = (-obj .B + sqrt(delta )) / (2 * obj .A);
21+ end
22+
23+ function plot(obj ,ax )
24+ % Plot a*x^2 + b*x + c around its axis of symmetry
25+ delta = calculateDelta(obj );
26+ x0 = - obj .B/(2 * obj .A);
27+ x1 = abs(sqrt(delta ))/obj .A;
28+ x = x0 + linspace(-x1 ,x1 );
29+ y = obj .A* x .^ 2 + obj .B* x + obj .C;
30+ plot(ax ,x ,y )
31+ xlabel(" x" )
32+ ylabel(sprintf(" %.2fx^2%+.2fx%+.2f" ,obj .A,obj .B,obj .C))
33+ end
34+ end
35+
36+ methods (Access = private )
37+ function delta = calculateDelta(obj )
38+ delta = obj .B^ 2 - 4 * obj .A* obj .C;
39+ end
40+ end
41+ end
0 commit comments