필터 지우기
필터 지우기

Help with linear regression function

조회 수: 16 (최근 30일)
Jesus Alejandro Rodriguez Morales
댓글: 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!

채택된 답변

Image Analyst
Image Analyst 2020년 10월 1일
Homework hint: Use the backslash operator. See the FAQ:
They do it there.
  댓글 수: 2
Jesus Alejandro Rodriguez Morales
Thank you, it's done
parsa soleimani
parsa soleimani 2021년 2월 22일
if you have the answer now can you send it please?

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Erandi T. Sandarenu
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

Erandi T. Sandarenu
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
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
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]
x = 1×4
1 2 3 4
matrix = [x; ones(1,length(x))]'
matrix = 4×2
1 1 2 1 3 1 4 1
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.
m = 2×4
1 2 3 4 1 1 1 1
matrix = m' % Transpose it.
matrix = 4×2
1 1 2 1 3 1 4 1
and then transposes it, with the apostrophe operator, to make the 1s be in the right column instead of the bottom row.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by