# plotting a line of best fit using a for loop

5 views (last 30 days)
C.G. on 22 Oct 2021
Commented: Dave B on 25 Oct 2021
I have the code to plot a line of best fit through my data but now I am trying to do this for multiple data sets in a for loop but it gives me errors that the vectors must be the same length. I know my indexing is wrong somewhere but I cant work out where.
I want it to loop through each column of my 7x2 matrix, and calculate the line of best fit for each column, and tell me the gradient and angle of the line.
for a = 1:num_files
p = polyfit(x(a),y(a),1);
Bfit = polyval(p(a),x);
scatter(x,y)
hold on
set(gca, 'XDir','reverse')
ylim([-0.127 -0.105]);
plot(x,Bfit(a),'-b')
pause(0.5)
angle(a) = rad2deg(atan(p(1))); %angle of the line
end
Error using plot
Vectors must be the same length.

Dave B on 22 Oct 2021
Edited: Dave B on 22 Oct 2021
you're plotting your x values against a scalar (Bfit(a)). I'm a little unclear about what you're tring to do here (your polyfit is on a single value, not the whole column)...you can resolve your error (in a sense) by plot(x,Bfit) but it's hard to believe that's what you want. Here's a guess:
for a = 1:width(x)
p = polyfit(x(:,a),y(:,a),1);
Bfit = polyval(p,x(:,a));
cla; % do you want to clear between plots? Or keep accumulating them?
scatter(x(:,a),y(:,a))
hold on
set(gca, 'XDir','reverse')
ylim([-0.127 -0.105]);
plot(x(:,a),Bfit,'-b')
pause(0.5)
angle(a) = rad2deg(atan(p(1))); %angle of the line
end
C.G. on 25 Oct 2021
Edited: C.G. on 25 Oct 2021
I have a series of x and y coordinates in the file I have attached here. I just want to plot a line of best fit through them and tell me the angle the line of best fit is at.
Each column is a new series of data, so I want it to loop through each column.
I didnt know how to do it so I searched the forum for some example code and that code above is the closest to what I want, I dont know if its exactly what I want it to do.
Dave B on 25 Oct 2021
I think that's about what you're accomplishing here, but did you want to plot them both on the same axes? Or maybe on separate axes? I attached both versions below...
figure(1)
for a = 1:width(x)
p = polyfit(x(:,a),y(:,a),1);
Bfit = polyval(p,x(:,a));
scatter(x(:,a),y(:,a),'SeriesIndex',a,'DisplayName',"Data " + a)
hold on
plot(x(:,a),Bfit,'SeriesIndex',a,'DisplayName',"Fit " + a)
set(gca, 'XDir','reverse')
ylim([-0.127 -0.105]);
angle(a) = rad2deg(atan(p(1))); %angle of the line
end
legend
%%
figure(2)
for a = 1:width(x)
p = polyfit(x(:,a),y(:,a),1);
Bfit = polyval(p,x(:,a));
nexttile
scatter(x(:,a),y(:,a),'SeriesIndex',a)
hold on
plot(x(:,a),Bfit,'SeriesIndex',a)
set(gca, 'XDir','reverse')
ylim([-0.127 -0.105]);
angle(a) = rad2deg(atan(p(1))); %angle of the line
end