Help with linear fit

9 ビュー (過去 30 日間)
aurc89
aurc89 2014 年 2 月 7 日
コメント済み: aurc89 2014 年 2 月 7 日
Given a curve (x vs y) I need to do a linear fit but only between two points x1 and x2 of that curve. Then, I need to calculate the slope of this line. Could you suggest me the fastest way to do that? Thanks.

採用された回答

Mischa Kim
Mischa Kim 2014 年 2 月 7 日
編集済み: Mischa Kim 2014 年 2 月 7 日
Here is one way:
x = 0:0.05:1; % define data
y = sin(x).^2;
x1 = x(10); % define interval
x2 = x(20);
xrange = x(find(x == x1):find(x == x2)); % pick out x and y vals in interval
yrange = y(find(x == x1):find(x == x2));
p = polyfit(xrange, yrange, 1); % do linear curve fit
yfit = polyval(p, xrange);
figure
hold on; grid; box
plot(x,y,xrange,yfit,'-r')
The first element of p is the slope of the linear curve.
  1 件のコメント
aurc89
aurc89 2014 年 2 月 7 日
It works, thank you very much!

サインインしてコメントする。

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2014 年 2 月 7 日
Here's how:
tf = x > x1 & x < x2 % true for x1 < x < x2
p = polyfit(x(tf), y(tf),1) % fit on selection
  1 件のコメント
aurc89
aurc89 2014 年 2 月 7 日
Thanks Jos!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeInterpolation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by