以图形方式显示线的斜率

时间:2014-07-29 10:32:45

标签: matlab

通过下面的代码,我们可以使用polyfit构造一组点并在它们上面插入一条线。最后一个函数返回两个变量。第一个变量是拟合红线的斜率。我想标记拟合线的斜率,如下图所示,使用一条黑色小线和一个显示斜率a的小文本。你能建议我们怎么做吗?

clear all
close all
clc
x = 0:0.01:2; 
noise = 0.8*randn(size(x));
y = 5*x + noise;
plot(x,y,'ko','MarkerSize', 2)
f = polyfit(x, y, 1) ;
y = f(1)*x + f(2); 
hold on
plot(x,y,'r--','LineWidth',2)

enter image description here

1 个答案:

答案 0 :(得分:1)

你可以这样做:

x_start = 1; % or wherever you want the line to start
y_start = 1; % or wherever you want the line to start
x_end = 1.3; % or wherever you want the line to end
y_end = f(1)*(x_end-x_start) + y_start;
line([x_start x_end],[y_start y_end],'Color','k');
text(x_start+0.2,y_start+0.5,['a = ' num2str(f(1))]); % adjust x & y offsets to suit
相关问题