필터 지우기
필터 지우기

Least Squares Regression, Help me find the error in my code!

조회 수: 1 (최근 30일)
SB
SB 2012년 10월 26일
Suppose the curve you're fitting can follow the form
y = an*x^n+ an-1*x^(n-1)+...+ a1x + a0
x and y are two column vectors of the same size and n is the degree of the polynomial. A is an array of the coefficients, in the order from an to a0.
Solve for A, and the e, the array of the residuals.
Here's what I have: function [A,e] = MyPolyRegressor(x, y, n)
for i= 1:n
x(i)=x.^(n-1);
end;
A=x/y;
e=A*x-y;
Whenever I run it, it says, "In an assignment A(I) = B, the number of elements in B and I must be the same." Please help!

답변 (2개)

Matt J
Matt J 2012년 10월 26일
편집: Matt J 2012년 10월 26일
In
x(i)=x.^(n-1);
the left hand side is a scalar location and the right hand side is not a scalar. So there's no room for it. I don't really understand why you're trying to overwrite x with powers of itself like x.^(n-1).
You should consider the VANDER command. I'm assuming you're not allowed to use POLYFIT.
  댓글 수: 3
SB
SB 2012년 10월 26일
I'd try that, but I'm trying to avoid using any commands beyond basic array ones. I was thinking something like
for i = 1:n
b(i) = x(i)^(n-i) ;
end
A=b\y';
e=A*b-y;
I can't quite get the answer though.
Matt J
Matt J 2012년 10월 26일
편집: Matt J 2012년 10월 26일
b=ones(length(x),n+1);
for i = 0:n-1
b(:,i+1) = x(:).^(n-i) ;
end

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


Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 26일
There is a problem in your x array size, it should be a matrix (nxm) where m is the length of y and m is the lenngth of unknown variables
  댓글 수: 1
SB
SB 2012년 10월 26일
I fixed that in my current code (shouldve been b*A rather than A*b), but I'm still getting the wrong answer ( the correct answer and my new code is posted above).

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by