1/8
Looks like no tags are added yet.
command to find polynomial which fits the above data if the function is linear, quadratic, cubic, or 5th order
% a. Linear (degree 1)
p_linear = polyfit(x, y, 1);
% b. Quadratic (degree 2)
p_quad = polyfit(x, y, 2);
% c. Cubic (degree 3)
p_cubic = polyfit(x, y, 3);
% d. 5th order (degree 5)
p_5th =polyfit(x, y, 5);
command to plot the given set of points with the curve fitting polynomials
command for displaying the polynomial coefficients in the command window
disp('Linear coefficients [p1, p0]:');
disp(p_linear); 0.0000, 8.0000;
disp('Quadratic coefficients [p2, p1, p0]:');
disp(p_quad); -0.6429; 7.0714; -9.5714;
disp('Cubic coefficients [p3, p2, p1, p0]:');
disp(p_cubic); 0.0000; -0.6429; 7.0714; -9.5714;
disp('5th order coefficients [p5, p4, p3, p2, p1, p0]:');
disp(p_5th); -0.0000; 0.0833; -1.8333; 13.9167; -42.1667; 50.0000;
command to plot the given set of points with the curve fitting polynomials
x_fit = linespace(min(x), max(x), 200);
command to evaluate the polynomials over the smooth range
y_linear = polyval(p_linear, x_fit);
y_quad = polyval(p_quad, x_fit);
y_cubic = polyval(p_cubic, x_fit);
y_5th = polyval(p_5th, x_fit);
command to create plot figure
figure;
plot(x, y, 'ko', 'MarkerFaceColor', 'k', 'MarkerSize', 8, 'DisplayName', 'Data
Points');
hold on;
plot(x_fit, y_linear, 'r--', 'LineWidth', 1.5, 'DisplayName', 'Linear Fit');
plot(x_fit, y_quad, 'g-', 'LineWidth', 1.5, 'DisplayName', 'Quadratic Fit');
plot(x_fit, y_cubic, 'b-.', 'LineWidth', 1.5, 'DisplayName', 'Cubic Fit');
plot(x_fit, y_5th, 'm:', 'Linewidth, 2.0, ‘DisplayName,‘ 5th Order fit’);
command to format the plot
xlabel('x');
ylabel('y');
title('Curve Fitting Polynomials');
legend('Location', 'south');
grid on;
hold off;
command for the best matching polynomial explanation
fprintf('\n--- Question 3 Answer ---\n');
fprintf(['The 5th order polynomial (or Quadratic depending on context) provides
exact fitting:\n' ...
'- Quadratic fit: captures the symmetric inverted parabolic trend (y peaks at
x=5,6).\n' ...
'- 5th order fit: passes through ALL 6 data points perfectly because degree = N -1.\n']);
The 5th order polynomial (or Quadratic depending on context) provides exact fitting:
- 'Quadratic fit: captures the symmetric inverted parabolic trend (y peaks at
x=5,6).'
- '5th order fit: passes through ALL 6 data points perfectly because degree = N - 1.’
command for line interpolation at x=5.5
y_interp = interp1(x, y, 5.5, 'linear');
fprintf('\n--- Question 4 Answer ---\n');
fprintf('The interpolated y-value at x = 5.5 using linear interpolation is:
%.2f\n', y_interp);
The interpolated y-value at x=5.5 using linear interpolation is: 10.00