How do i plot the line of best fit?

241 views (last 30 days)
So in Pressure Experiments.mat, there is (6,32) data set. I need the whole 5th row and the 6th row of this data.So I made a scatter plot of this data with :
%Load experimental data
load('PressureExperiments.mat', 'PData')
disp(PData)
%Seperating data
A = PData(5,:) %petrol pressure data
B = PData(6,:) %Number of escaping hydrocarbons
figure(1)
scatter(A,B)
How do i make a line of best fit for this? and plot the best line on the same figure?
Thanks

Accepted Answer

Star Strider
Star Strider on 16 Apr 2020
Try this:
%Load experimental data
load('PressureExperiments.mat', 'PData')
% disp(PData)
%Seperating data
A = PData(5,:); %petrol pressure data
B = PData(6,:); %Number of escaping hydrocarbons
P = polyfit(A, B, 1); % Linear Fit
Bfit = polyval(P, A);
figure(1)
scatter(A,B)
hold on
plot(A, Bfit,'-r')
hold off
grid
If you want statistics on the fit, and you have the Statistics and Machine Learning Toolbox, use the regress or fitlm functions.
.
  5 Comments
Nathen Eberhardt
Nathen Eberhardt on 16 Apr 2020
I got one more question, how would i find the value of the number of hyrdrocarbons ecaping when the petrol pressure is ten? So How do i find B when A = 10 using the best fit line?
Star Strider
Star Strider on 16 Apr 2020
The easiest way (assuming that the relation holds beyond the region-of-fit, not always a reliable assumption):
B = polyval(P, 10)
producing:
B =
66.3339
In general, it is not advisable to extrapolate that far beyond the region of it, unless (on the basis of other knowledge) you can be reasonably certain that the linear (or any other) relaionship is generally valid. With a mathematical model of this relationship, it would be possible to use linear or nonlinear parameter estimation techniques to devise a relation that would ber more generally applicable.
.

Sign in to comment.

More Answers (1)

the cyclist
the cyclist on 16 Apr 2020
Use polyfit to find the line of best fit.
Use the plot command to plot that line
Use the hold command so that the new plot does not overwrite the scatter plot.

Community Treasure Hunt

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

Start Hunting!