define function to data set
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello, please, if you could help me to fit a function to a data series, I understand that the matlab 'fit' function works excellent, but I don't know how to implement it. What I have to do is fit the best possible function to the data series, but the problem that I have two series 'x1' and 'x2', e 'y1' and 'y2', where they all go in a single figure, for which I write down the code I have. I attach the data. Thanks greetings.
load x1.txt , load x2.txt , load y1.txt , load y2.txt
plot(x1,y1,'or',x2,y2,'or')
0 commentaires
Réponses (1)
Mathieu NOE
le 25 Juin 2021
hello
here you are my friend
result :
code :
clearvars
load x1.txt , load x2.txt , load y1.txt , load y2.txt
% merge the two data sets
x = [x1;x2];
y = [y1;y2];
% reshape data from array to vector
xx = x(:);
yy = y(:);
% sort xx data in ascending order
[xx,ind] = sort(xx);
yy = y(ind);
% Fit a polynomial p of degree "degree" to the (x,y) data:
degree = 4;
p = polyfit(xx,yy,degree);
% Evaluate the fitted polynomial p and plot:
f = polyval(p,xx);
figure(1);plot(xx,yy,'o',xx,f,'-')
legend('data','poly fit')
2 commentaires
Mathieu NOE
le 29 Juin 2021
hello
here I added the string in the legend
clearvars
load x1.txt , load x2.txt , load y1.txt , load y2.txt
% merge the two data sets
x = [x1;x2];
y = [y1;y2];
figure(1);plot(x1,y1,'*b',x2,y2,'or',x,y,'dk')
% reshape data from array to vector
xx = x(:);
yy = y(:);
% sort xx data in ascending order
[xx,ind] = sort(xx);
yy = y(ind);
figure(2);plot(x,y,'*b',xx,yy,'or')
% Fit a polynomial p of degree "degree" to the (x,y) data:
degree = 4;
p = polyfit(xx,yy,degree);
% Evaluate the fitted polynomial p and plot:
f = polyval(p,xx);
eqn = poly_equation(p); % polynomial equation (string)
figure(3);plot(xx,yy,'o',xx,f,'-')
legend('data',eqn)
function eqn = poly_equation(a_hat)
eqn = " y = "+a_hat(1);
for i = 2:(length(a_hat))
if sign(a_hat(i))>0
str = " + "
else
str = " "
end
if i == 2
eqn = eqn+str+a_hat(i)+"*x";
else
eqn = eqn+str+a_hat(i)+"*x^"+(i-1)+" ";
end
end
eqn = eqn+" ";
end
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!