How do I can build a MATLAB code to fit the following equation using least square sense ?

here is my equation : y=a+bx;
x=[1 2 3 4 5 6];
y=[3.5 0.5 -1.5 -3 -4.5 -7 ];
I've try this code
clc;
clear all;
close all;
%we need to do a line fitting to the following equation (y=a+bx)
X=[1; 2; 3; 4; 5; 6]; %
Y=[3.5; 0.5; -1.5; -3; -4.5; -7];
N=length(X);
AB=(X'.*X)*(X'.*Y); %coefficient matrix [a,b]
plot(X,Y,'o')
hold;
plot(AB(1:3,:),AB(4:6,:),'r-');
is that right? and what is the values of a,b

 Accepted Answer

The X dependes on how you want to fit your line to the data.
e.g., then X will be a series of stacked vertically upto the end of the data number.

11 Comments

is it like this
clc;
clear all;
close all;
%This program is to solve proplem in HW"8"
%we need to do a line fitting to the following equation (y=a+bx)
x=[1; 2; 3; 4; 5; 6]; %
y=[3.5; 0.5; -1.5; -3; -4.5; -7];
N=length(x);
X=[ones(N,1),x];%write x in this format to prepare for fitting process
Y=y;
AB=(X'.*X)*(X'.*Y); %coefficient matrix [a,b]
plot(X,Y,'o')
hold;
plot(AB(1)+AB(2),'r-');
if yes an error will happen
''Matrix dimensions must agree.
Error in HW8_least_square_Method (line 11)
phi=(X'.*X)\(X'.*Y); %coefficient matrix [a,b]''
AB = X\y;
y_hat = X*AB;
plot(x,y,'b-',x,y_hat,'r-');
Please try to see how it fits to your thought.
x=[1; 2; 3; 4; 5; 6]; %
y=[3.5; 0.5; -1.5; -3; -4.5; -7];
N=length(x);
X=[ones(N,1),x];
b = X\y;
y_hat = X*b;
plot(x,y,'bo', x,y_hat,'r-');
This is good enough.

Sign in to comment.

More Answers (0)

Products

Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!