How to plot a single column of values with a linear regression line through it

I have a column that I wann plot and have a regression line go through it, How would I do that?
my code so far is:
figure(1)
title('Phase1')
plot(FG)

5 件のコメント

darova
darova 2020 年 2 月 19 日
What about polyfit?
isamh
isamh 2020 年 2 月 24 日
thanks for the reply, I tried two different ways and both didnt seem to work. Would it be possible to do the regression line for just one column? I know we can plot one column like this: plot(X) and plost the columns values against number of rows. I know i didnt do that for the code i listed but how would i do both?
1)
figure(1)
X = Fengd_1;
Y = WATT_HR_1;
plot(X,Y,'.b')
p = polyfit(X,Y,1);
f = polyval(p,X);
hold on
plot(X,f,'--r')
2)
figure(1)
X = Fengd_1;
Y = WATT_HR_1;
format long
B1 = X\Y;
YCalc1 = B1*X;
scatter(X,Y)
hold on
plot(X,YCalc1)
title('Phase1')
grid on
Attach X and Y in a mat file so we can show you.
save('answers.mat', 'X', 'Y');
In the meantime, see my attached polyfit() demo.
darova
darova 2020 年 2 月 24 日
  • I added the: save('answers.mat', 'X', 'Y'); to both codes and still didnt the regression line.
Image Analyst can you cooperate?
isamh
isamh 2020 年 2 月 24 日
編集済み: isamh 2020 年 2 月 24 日
Lol I just noticed what was wrong with that. Thought he wanted me to do something else, I’m unable to provide the data now and was wondering if we could just use random data. Forgot to mention that i have some NAN rows with both columns, would that effect the results?

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

 採用された回答

darova
darova 2020 年 2 月 24 日
Here is a simple example (i made it special for you)
N = 20;
x = linspace(0,3,N);
y = 2*x + rand(1,N);
p = polyfit(x,y,1);
y1 = polyval(p,x);
plot(x,y,'.r')
hold on
plot(x,y1,'b')
hold off
  • Forgot to mention that i have some NAN rows with both columns, would that effect the results?
Then you should do interpolation without NaN
ix = ~isnan(y); % choose indices that are not NaN
x1 = x(ix);
y1 = y(ix);
p = polyfit(x1,y1,1);
y2 = polyval(p,x1);

2 件のコメント

isamh
isamh 2020 年 2 月 24 日
Trued that but I believe the columns are now unequal lengths. I get this error message: error with p1=polyfit(X1,Y1,1);
darova
darova 2020 年 2 月 24 日
Please post the entire error and code you used

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Linear and Nonlinear Regression についてさらに検索

質問済み:

2020 年 2 月 19 日

コメント済み:

2020 年 2 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by