如何绘制一条曲线的两个斜率

时间:2014-03-29 17:03:08

标签: matlab plot matlab-figure

我在Matlab中有一条曲线。我想绘制两个斜坡;第一个斜坡用于点1,2,3和4.第二个斜率用于绘制其余点。见图:

enter image description here

1 个答案:

答案 0 :(得分:2)

当你说“绘制两个斜坡”时,我会假设您想要绘制最接近数据两部分的线。为此,您需要执行曲线拟合程序,例如最小二乘法。有关MATLAB中最小二乘逼近的更多信息,请参阅此问题:How do I use the least squares approximation in MATLAB?

我将假设您的数据存储在向量xy中。

%//number of points for the first part of the curve:
n=4;

%// Separate (x,y) into (x1,y1) and (x2,y2)
x1 = x(1:n); x2=x(n+1:end);
y1 = y(1:n); y2=y(n+1:end);

%// fit a line y=A1*x+A2 to the first set of points:
M=[x1(:) ones(length(x1),1)];
A = M\y1(:); %//A(1) is your slope, A(2) is your y-intercept

%// fit a line y=B1*x+B2 to the second set of points:
M=[x2(:) ones(length(x2),1)];
B = M\y2(:); %//B(1) is your slope, B(2) is your y-intercept

%//Plot:
hold on
fplot(@(x)A(1)*x+A(2),[min(x1) max(x1)])
fplot(@(x)B(1)*x+B(2),[min(x2) max(x2)])