(c) The following data shows the number of people expected in a coffee shop between the hours 09.00-18.00. You are required to build a polynomial model of this and determine the coefficients that can be used to predict a value of y, given an input value x. Assume that the degree of the polynomial is 5, and y is already in the MATLAB workspace (i.e. x needs to be generated).
Expert Answer
Code:
%Define a function
function [p, yf] = Mypolyfit (x, y, n)
%If arguments not equals 3
if (nargin != 3)
%Display
usage (“polyfit (x, y, n)”);
%End
endif
%If x and y not in proper format
if (! (isvector (x) && isvector (y) && size (x) == size (y)))
%Display message
error (“Error!!!”);
%End
endif
%If n not in proper format
if (! (isscalar (n) && n >= 0 && ! isinf (n) && n == round (n)))
%Error
error (“Error!!!”);
%End
endif
%Check
y_is_row_vector = (rows (y) == 1);
%Compute length
l = length (x);
%Reshape
x = reshape (x, l, 1);
%Reshape
y = reshape (y, l, 1);
%Define X
X = (x * ones (1, n+1)) .^ (ones (l, 1) * (0 : n));
%Compute value
p = X y;
%If value is 2
if (nargout == 2)
%Compute value
yf = X * p;
%If value is true
if (y_is_row_vector)
%Assign value
yf = yf.’;
%End
endif
%End
endif
%Compute value
p = flipud (p);
%If condition matches
if (y_is_row_vector && rows (x) == 1)
%Assign value
p = p’;
%End
endif
%End
endfunction
%Define x values
x = [9 10 11 12 13 14 15 16 17 18];
%Define y values
y = [20 25 30 40 80 75 35 10 20 60];
%Display message
disp(‘The coefficients of polynomial are ‘)
%Call method
Mypolyfit(x,y,5)