필터 지우기
필터 지우기

define function to data set

조회 수: 4 (최근 30일)
ignacio bobadilla tapia
ignacio bobadilla tapia 2021년 6월 25일
댓글: Mathieu NOE 2021년 6월 29일
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
ignacio bobadilla tapia 2021년 6월 28일
@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에서 Regression에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by