plotting a line of best fit using a for loop

7 views (last 30 days)
C.G.
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)
grad(a) = p(1); %gradient of the line
angle(a) = rad2deg(atan(p(1))); %angle of the line
end
Error using plot
Vectors must be the same length.

Accepted Answer

Dave B
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)
grad(a) = p(1); %gradient of the line
angle(a) = rad2deg(atan(p(1))); %angle of the line
end
  2 Comments
Dave B
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...
load xy
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]);
grad(a) = p(1); %gradient of the line
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]);
grad(a) = p(1); %gradient of the line
angle(a) = rad2deg(atan(p(1))); %angle of the line
end

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by