Please optimize this code by using a loop to display the polynomial coefficients.
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
clearvars, clc, close all;
% Please optimize this code by using a loop to display the polynomial coefficients.
load t2pb2data.mat
g=g(:);
t=t(:);
plot(t,g,'g*');
xlabel('t');ylabel('g');
N=10;
z=polyfit(t,g,N);
p10=z(11);
fprintf('p10=%.4f.\n',p10);
p9=z(10);
fprintf('p9=%.4f.\n',p9);
p8=z(9);
fprintf('p8=%.4f.\n',p8);
p7=z(8);
fprintf('p7=%.4f.\n',p7);
p6=z(7);
fprintf('p6=%.4f.\n',p6);
p5=z(6);
fprintf('p5=%.4f.\n',p5);
p4=z(5);
fprintf('p4=%.10f.\n',p4);
p3=z(4);
fprintf('p3=%.10f.\n',p3);
p2=z(3);
fprintf('p2=%.10f.\n',p2);
p1=z(2);
fprintf('p1=%.12f.\n',p1);
p0=z(1);
fprintf('p0=%.16f.\n',p0);
tfit=linspace(min(t),max(t));
gfit=polyval(z,tfit);
hold on
plot(tfit,gfit,'b');
ghat=polyval(z,t);
gbar=mean(g);
R2=1-sum((g-ghat).^2)/sum((g-gbar).^2)
legend('Data points measured','poly curve fitting line')
0 Kommentare
Antworten (1)
Walter Roberson
am 8 Dez. 2023
fprintf('p%d=%.8f.\n', K, z(K+1))
However, you are using different widths for different coefficients. You will need to build a vector indicating what width to use, and you will need to either compute the format or else use the obscure fprintf %* facility to use data as a format width
For example
fprintf("p%d=%." + FieldWidths(K+1) + "f.\n'", K, z(K+1))
0 Kommentare
Siehe auch
Kategorien
Mehr zu Polynomials finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!