% IAP2007 Introduction to MATLAB: Interface and Basics % Instructor: Violeta Ivanova, violeta@mit.edu % EXERCISE 2 Curve Fitting % MATLAB vectors, polynomials, matrix operations, curve fitting, plotting. % The coordinates (x1,y1), (x2,y2), (x3,y3) and (x4,y4) of four points are % given: (1, 54), (5, 82), (8, 40), and (10, 10). % Find a cubic equation y(x) that passes through the four points i.e.: % y = c1*x^3 + c2*x^2 + c3*x + c4 % Fit also a straight line and a quadratic curve to the points. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % A. VECTORS % A1. Define column vectors X and Y from the points' coordinates such that % X = (x1, x2, x3, x4) and Y = (y1, y2, y3, y4) % Create a column vector X by transposing a row vector: X = [1 5 8 10]; X=X' % Create a column vector Y by entering its elements row by row: Y = [54; 82; 40; 10] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % B. CURVE FITTING % Compute straight line, quadratic, and cubic fits with function POLYFIT. % B1. Straight line fit: C1 = polyfit(X, Y, 1); % B2 Quadratic fit: C2 = polyfit(X, Y, 2); % B2 Cubic fit: C3 = polyfit(X, Y, 3); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % C. POLYNOMIALS % C1. Compute a cubic curve, a quadratic curve, and a straight line over an % x interval from 0 to 10 at a step of 0.1. Hint: use function POLYVAL. x = [0 : 0.1 : 10]; y1 = polyval(C1, x); y2 = polyval(C2, x); y3 = polyval(C3, x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % D. PLOTTING % D1. Plot the cubic curve, quadratic curve, straight line, and four points % on the same figure. Note: use different colors and/or markers. % Hint: use functions PLOT, HOLD ON, and HOLD OFF. p = plot (x, y1, 'r-'); hold on; p2 = plot (x, y2, 'g-'); hold on; p1 = plot (x, y3, 'k-'); hold on; P = plot (X, Y, 'bo'); hold off; % D2. Add a title, X and Y labels, and a legend to the figure. % Hint: Use functions TITLE, XLABEL, YLABEL, and LEGEND. xlabel('X', 'FontSize', 12); ylabel('Y', 'FontSize', 12); title('CURVE FITTING TO POINTS', ... 'FontSize', 12, ... 'FontWeight', 'bold'); legend ('Cubic Fit', 'Quadratic Fit', 'Straight Line Fit', 'Data Points'); % D3. Customize the figure using the PROPERTY EDITOR. % D4. Save the figure in a JPEG file.