Help with linear regression function
14 ビュー (過去 30 日間)
古いコメントを表示
Jesus Alejandro Rodriguez Morales
2020 年 9 月 30 日
コメント済み: Image Analyst
2022 年 10 月 4 日
Hello, community.
Can someone help me with the following assignment.
Given a set of approximate x and y coordinates of points in a plane, determine the best fitting line in the least square sense. Using the standard formula of a line ax + b = y, compute a and b. That is, write a function that takes two row verctors of the same length called x and y as input arguments (containing x and y coordinates of points) and returns two scalars, a and b specifying the line, as output arguments.
I can't use polyfit
Thank you in advance!
0 件のコメント
採用された回答
Image Analyst
2020 年 10 月 1 日
Homework hint: Use the backslash operator. See the FAQ:
They do it there.
2 件のコメント
その他の回答 (2 件)
Erandi T. Sandarenu
2021 年 11 月 2 日
This was done without using backslash operator. But it works!
function [a b] = lin_reg(x,y)
X = mean(x);
Y = mean(y);
a = sum((x-X).*(y-Y))./sum((x-X).^2);
b = Y - a*X;
end
0 件のコメント
Erandi T. Sandarenu
2021 年 11 月 2 日
This was done by using the backslash operator.
function [a b] = lin_reg(x,y)
matrix = [x; ones(1,length(x))]';
x = matrix \ y';
a = x(1);
b = x(2);
end
2 件のコメント
Mohaddeseh Mohammadi
2022 年 10 月 4 日
Hello, Could you please explain the method you used? I can not understand what is matrix = [x; ones(1,length(x))]'; for.
Image Analyst
2022 年 10 月 4 日
It's easy just to try something and see. Make x a row vector of 4 elements and see what it gives:
x = [1,2,3,4]
matrix = [x; ones(1,length(x))]'
So it takes a row vector and puts a row of ones below it
m = [x; ones(1,length(x))] % Append row of 1s below our x row vector.
matrix = m' % Transpose it.
and then transposes it, with the apostrophe operator, to make the 1s be in the right column instead of the bottom row.
参考
カテゴリ
Help Center および File Exchange で Spline Postprocessing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!