How do i plot one best fit line for multiple data sets?
17 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I am trying to plot 3 sets of data on the same set of axes, and then plot one line of best fit through all the data sets.
I can display all the data on the same axis with no issues simply using plot, see image below

However, when i try to plot a line of best fit through this data, it only allows me to plot it for one data set at a time, see below.

This is not what i want to do, as each line only accounts for one data set rather than every data point on the graph. Does anyone know how i could fix this?
Thank you!
0 Kommentare
Antworten (2)
Star Strider
am 30 Dez. 2021
I would do something like this —
x1 = 0:0.5:10;
x2 = x1 + 2;
x3 = x1 - 0.5;
y1 = 1 + 0.2*x1 + randn(size(x1))*0.2;
y2 = 1.5 + 0.1*x2 + randn(size(x2))*0.1;
y3 = 0.5 + 0.3*x3 + randn(size(x3))*0.3;
DM = [x1, x2, x3;
ones(size([x1, x2, x3]))].';
B = DM \ [y1, y2, y3].'
LBF = DM * B;
figure
plot(x1, y1, '.')
hold on
plot(x2, y2, '.')
plot(x3, y3, '.')
plot(DM(:,1), LBF, '-r')
hold off
legend('y_1','y_2','y_3','Line of Best Fit', 'Location','best')
text(1, 3, sprintf('y = %.3f\\cdotx%+.3f',B))
The strategy here is to concatenate the independent variable vectors and the dependent variable vectors separately, then use them as ordinary independent and dependent variable vectors in the regression (linear here for simplicity). The independent variable vectors can be different values and different lengths (although the same lengths here) making this approach reasonably robust.
A nonlinear approach would proceed similarly, however if different parameters were to be estimated for different independnet and dependent variable vectors, all the sizes would have to be the same for all the vectors, requiring a different approach.
.
0 Kommentare
Image Analyst
am 30 Dez. 2021
Bearbeitet: Image Analyst
am 30 Dez. 2021
Not sure of your definition of best, but how about just taking the average
plot(x, data1, '-', 'LineWidth', 1);
hold on;
plot(x, data2, '-', 'LineWidth', 1);
plot(x, data3, '-', 'LineWidth', 1);
allData = (data1 + data2 + data3) / 3;
% allData may wiggle around a bit just like the actual data.
plot(x, allData, 'r-', 'LineWidth', 3);
% If you don't want the average data but want a line instead, then
% fit data to a line.
xTrain = [x(:); x(:), x(:)];
yTrain = allData(:);
lineCoefficients = polyfit(xTrain, yTrain, 1);
% Get a vector of line fit points for every x location
yFitted = polyval(coefficients, x);
plot(x, yFitted, 'm-', 'LineWidth', 2);
If you want to interpolate additional points in between your existing x points, you could certainly do that. See my attached spline interpolation demo.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Get Started with Curve Fitting Toolbox finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!