Lab 8 Assignment Due on 04/02 at the beginning of lab. Submit your m-file, diary
ID: 3741479 • Letter: L
Question
Lab 8 Assignment
Due on 04/02 at the beginning of lab.
Submit your m-file, diary showing a successful run, and figure.
1) Download
Lab 8 data2.mat
to your current directory from our shared folder.
Note:
The variable loaded from here is called
data
. Load the file in your workspace
from the command window to confirm. After loading
Lab 8 data2
in your code,
you must call on the variable in your code by
data
.
2) Write an m-file to load data from
Lab 8 data2.mat
and compute the least squares
approximation for the data. This should be the best fit
parabola
. The function
will have no input and no output.
Your function should work for any
.mat
file containing an
m×2 matrix,
where m is a positive integer.
•
The function should plot the data points and the approximating parabola
in one figure with a legend.
•
The function should print the equation of the parabola of best fit.
•
See the in-class exercise answer for plot and print formatting.
Note:
The equation of a parabola is
y = Ct^2 + Dt + E
Pseudo-code:
function lsaparabola
% Load data. The data has the to be in the same directory or sub-directory
% as this function. It’s file name should go in ’filename.mat’.
% Retrieve the size of the data.
% The data is ordered pairs (t,y) with the first column being the t values,
% and the second column being the y values.
% Form coefficient matrix A and the right hand side b in Ax = b.
% We are fitting the parabola y = Ct^2 + Dt + E. Given data points (t,y),
% we want to find the C, D, E that form the parabola that best fits this
% data.
Form A
Form b
% Find the least squares solution x. This found from the projection of b
% onto the column space of A.
% Retrieve the parameters C, D, E.
C = x(1); D = x(2); E = x(3); % actual MATLAB code
% Form the parabola y = Ct^2 + Dt + E to plot.
Form t as a linearly spaced vector between the
minimum and maximum t data values.
Form y, the parabola.
% Plot the data and the parabola of best fit on the same axes with
% appropriate formatting.
% Print the result.
% ’%f’, as opposed to ’%d’, prints the result as a floating point with
% out the scientific notation.
end
Explanation / Answer
%provide data to debug this code
load data2.mat
xs=data(:,1);
y=data(:,2);
A=[xs(1)^2 xs(1) 1;
xs(2)^2 xs(2) 1;
xs(3)^2 xs(3) 1];
b=[y(1);y(2);y(3)];
x=A;
C = x(1); D = x(2); E = x(3); % actual MATLAB code
points=min(xs):.1:ma(xs);
y_points=polyval(x,points);
plot(xs,y,'*',points,y_points)
legend('Data points','Parabola of best fit')
fprintf('The parabola of best fit is: (%f)t^2 + (%f)t + E ',x);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.