define function to data set

2 次查看(过去 30 天)
ignacio bobadilla tapia
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')

回答(1 个)

Mathieu NOE
Mathieu NOE 2021-6-25
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 个评论
ignacio bobadilla tapia
@Mathieu NOE Estimated how can I make the function (polynomial equation) appear in the figure ??
Mathieu NOE
Mathieu NOE 2021-6-29
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by