Writing my own polyfit function

26 ビュー (過去 30 日間)
SB
SB 2012 年 10 月 26 日
コメント済み: Max 2022 年 8 月 20 日
How would one write their own polyfit function using only mldivide and for loops?
I have a basic idea:
function [A,e] = MyPolyRegressor(x, y, n)
c=ones(n,1);
for i=1:n;
c(:,i)=x.^(i-1);
end
A=c\y
e=c*A-y
But it doesnt quite work.
  3 件のコメント
SB
SB 2012 年 10 月 26 日
Well, there's a dimension mismatch in line 4. Even when I switch c to c=ones(size(X)) to fix that issue, there are too many coefficients, none of which are correct.
Jan
Jan 2012 年 10 月 26 日
編集済み: Jan 2012 年 10 月 26 日
Because you didn't format your code properly (please learn how to do this...), it is not possible to find out, which one is the "line 4".
But with some guessing: "ones(n,1)" and even "ones(size(x))" create vectors, while the required Vandermonde-matrix needs the dimensions [length(x), n+1].

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

採用された回答

Jan
Jan 2012 年 10 月 26 日
編集済み: Jan 2012 年 10 月 26 日
function p = fPolyFit(x, y, n)
% Construct Vandermonde matrix:
x = x(:);
V = ones(length(x), n + 1);
for j = n:-1:1
V(:, j) = V(:, j + 1) .* x;
end
% Solve least squares problem:
[Q, R] = qr(V, 0);
p = transpose(R \ (transpose(Q) * y(:)));
% Equivalent: (V \ y)'
  1 件のコメント
SB
SB 2012 年 10 月 26 日
編集済み: SB 2012 年 10 月 26 日
For a weighted Least Squares problem, would you do function [A, e] = WeightedLeastSquares(X, Y, w,n)
X=diag(w)*X
Y=diag(w)*Y
X = X(:);
V = ones(length(X), n + 1);
for j = n:-1:1
V(:, j) = V(:, j + 1) .* X;
end
[Q, R] = qr(V, 0);
A= (R \ (transpose(Q) * Y(:)));
e= V*A-Y;
?

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

その他の回答 (1 件)

Vrushabh Bhangod
Vrushabh Bhangod 2018 年 5 月 19 日
編集済み: Walter Roberson 2018 年 6 月 10 日
function [p,mu,f] = plofit(x,y,n)
% x = input samples
% y = output function,n = order
m = length(x); %number of rows in the Vandermonde Matrix
V = zeros(m,n);
a = n;
for i = 1:m
v = zeros(1,n);
for j = a:-1:1
v(n+1-j) = realpow(x(i),j);
end
V(i,:) = v;
end
V(:,n+1)=ones(m,1);% adding 1 column to ones to the vandermonde matrix
%%QR method to compute the least squares solution for the coefficients,'p'
[Q,R] = qr(V,0);
p = transpose(R \ (transpose(Q) * y'));
f = polyval(p,x);
%%to find mean
mean = sum(x)/length(x);
sq = 0;
for i =1:length(x)
sq = sq + (x(i)-mean)^2;
end
sd = (sq/length(x))^0.5;
mu = [mean;sd];
end
  1 件のコメント
Max
Max 2022 年 8 月 20 日
Works perfect, Thanks!

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

Community Treasure Hunt

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

Start Hunting!

Translated by