define function to data set

10 views (last 30 days)
ignacio bobadilla tapia
ignacio bobadilla tapia on 25 Jun 2021
Commented: Mathieu NOE on 29 Jun 2021
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')

Answers (1)

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

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!