Hello, this is my matlab script that is supposed to take data from an excel spread sheet and use it to create a y = mx+b function by linear regression. Here is my code and attached is the excel spread sheet. The first row is the amount in gallons and the next two rows are the amount of time it took to move the gallons in seconds.
points = xlsread('data.xlsx');
n = size(points,1);
sum_x = 0;
sum_y = 0;
sum_xy = 0;
sum_x2 = 0;
for i = i:n
sum_x = sum_x + points(i,2);
sum_y = sum_y + points(i,3);
sum_xy = sum_xy + points(i,2)*(points(i,3));
sum_x2 = sum_x2 + (points(i,2)^2);
end
a1 = (n*sum_xy - sum_x*sum_y)/(n*sum_x2 - sum_x2);
a0 = (sum_y/n)-a_1*(sum_x/n);
y_new = a1*x + a_0;
THank you for your help.

5 comentarios

Brendan Hamm
Brendan Hamm el 26 de Abr. de 2015
So the question is what? Why this is not a proper linear regression? Why we do not require the loop?
Ryan Albawab
Ryan Albawab el 26 de Abr. de 2015
well I have been able to successfully get values for a1 and a0 from a excel spread sheet, the problem is whenever i try to do the
Y_new = a1*x + a0;
I get a answer from matlab saying that
y = Undefined function or variable 'x'.
I dont know how to go around it.
Brendan Hamm
Brendan Hamm el 27 de Abr. de 2015
It is helpful to everyone here if you state any errors you have. See Mohammad's answer, it should help.
Image Analyst
Image Analyst el 27 de Abr. de 2015
You haven't defined your x variable yet, like Mohammad did where he called x "gModel" - a more descriptive name than the generic "x". It looks like his code should work. If it does, Vote for it and then click "Accept this answer" .
Or Hirshfeld
Or Hirshfeld el 27 de Abr. de 2015
I would use curve fitting function in matlab instead of summing in iterations and calculated formulas.

Iniciar sesión para comentar.

 Respuesta aceptada

Mohammad Abouali
Mohammad Abouali el 27 de Abr. de 2015
% First COLUMN is galon, the next two columns are amount of time required
% to remove that amount of gallons. I assumed you have two sets of
% measurements that's why there are two columns.
data=[ 0.50 66 70; ...
0.75 100 95; ...
1.00 129 135; ...
1.25 161 159; ...
1.50 198 190; ...
1.75 230 232; ...
2.00 265 250];
% Fitting a a polynomial t=a1*g+a0; g: Gallon, t: time
g=[data(:,1);data(:,1)];
tMeasured=[data(:,2);data(:,3)];
a=polyfit(g, tMeasured,1);
% Plot1
gModel=min(g):0.01:max(g);
tModelled=polyval(a,gModel);
figure
plot(gModel,tModelled,'r-','LineWidth',2);
hold on
plot(g,tMeasured,'kx','MarkerSize',10)
legend('Fitted Line','Measured','Location','NorthWest');

Más respuestas (0)

Categorías

Preguntada:

el 26 de Abr. de 2015

Comentada:

el 27 de Abr. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by