Writing my own polyfit function
Mostrar comentarios más antiguos
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 comentarios
Please explain what "doesn't quite work" mean explicitly. Do you get an error message or do the results differ from your expectations? This forum is fine for solving problem, but bad for guessing them.
Notes: The POWER operation is very expensive. Better multiply x cummulatively.
SB
el 26 de Oct. de 2012
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].
Respuesta aceptada
Más respuestas (1)
Vrushabh Bhangod
el 19 de Mayo de 2018
Editada: Walter Roberson
el 10 de Jun. de 2018
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 comentario
Max
el 20 de Ag. de 2022
Works perfect, Thanks!
Categorías
Más información sobre Linear Algebra en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!