In: Mechanical Engineering
Suppose it is known that the graph of the function y = ax3 + bx2 + cx + d passes through four given points (xi, yi ), i = 1, 2, 3, 4. Write a userdefined function that accepts these four points as input and computes the coefficients a, b, c, and d. The function should solve four linear equations in terms of the four unknowns a, b, c, and d. Test your function for the case where (xi , yi) = (-2, -20), (0, 4), (2, 68), and (4, 508), whose answer is a = 7, b = 5, c = -6, and d = 4.
MATLAB Script:
close all
clear
clc
x = [-2 0 2 4];
y = [-20 4 68 508];
coeffs = fit_poly(x, y);
fprintf(\'Solution:\\n\\t\')
fprintf(\'a = %.2f\\n\\tb = %.2f\\n\\tc = %.2f\\n\\td = %.2f\\n\', coeffs)
function coeffs = fit_poly(x, y)
% (x, y): 4 data points
% coeffs: [a b c d]
% We need to solve the system A*coeffs = y
% Where A = [x^3 x^2 x 1]
x = x(:); y = y(:); % Turn into column vectors
A = [x.^3 x.^2 x ones(size(x))];
coeffs = A\\y; % Solve the system using \'\\\' operator
end
After the test of function output is:
a = 7.00
b = 5.00
c = -6.00
d = 4.00
After the test of function output is:
a = 7.00
b = 5.00
c = -6.00
d = 4.00