In: Mechanical Engineering
Use Matlab and write entier script
Problem 1.
Using the information above, find y(n) for all n between 1:N.
y(tn)=mx(tn)+b+r(tn)
y=mx+b
Plot the points on a graph, without connecting them with a line. Use a command like:
plot( x, y, ‘.r’ )
Now we want to find the “best fit” solution. As was mentioned before, this was defined in the prior exercise. (You may wish to read this to understand how the algorithm works.) Use the MATLAB code below.
You have the vectors x and y already. You need a vector I, which is a column which each element equal to 1.
Programming Steps:
I = ones(length(x),1);
u = [ x , I ];
w = (u’ * u) \ ( u’ * y) ;
The result is an estimate of the values of m and b. The estimate for m is w(1) and the estimate for b is w(2). The resulting estimate for y is:
y_est = u * w;
MATLAB CODE:
clc;
clear;
n=10; %number of elements in x
m=5; %assumed m
b=1; %assumed b
r=(linspace(1,3,n))';
x=(1:1:n)'; %array x
y=m*x+b+r; %function for y
%best fitting
I = ones(length(x),1);
u = [x,I];
w = (u'*u)\(u'*y);
y_est = u*w;
%plotting
figure(1) % plot showing y v/s x
plot (x,y,'*','color','r');
xlabel('x ','FontSize', 16); ylabel('y(x) and
y_estimate','FontSize', 16);
title('y v/s x, with best fit','FontSize', 20);
grid on
hold on
plot (x,y_est,'color','k');
hold off
SAMPLE OUTPUT:
PLEASE COMMENT IF ANY DOUBTS OR ERROR ARE THERE.. I WILL HELP YOU..