# plotting a line of best fit using a for loop

1 次查看（过去 30 天）
C.G.2021-10-22

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 2021-10-22

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
##### 2 个评论显示隐藏 1更早的评论
Dave B 2021-10-25
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

### Community Treasure Hunt

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

Start Hunting!

Translated by