MATLAB: I get the wrong polyfit

MATLAB and Simulink Student Suitepolyfit

ftz = [1.4846i 1.1582i];
P_pie=poly(ftz);%roots=ftz
for j=-2:0.01:2
k=floor(((j+2)/0.01)+1);
P_pie_subs(k)=polyval(P_pie,j*1i);
P_subs(k)=P_pie_subs(k)/(2*sqrt(2));
end
x=(-2:0.01:2);
x=x*1i;
P=polyfit(x,P_subs,2);
roots(P)
% ans =
% 0.115192576001519 + 1.337122816059961i
% -0.115192576001520 + 1.337122816059962i

Best Answer

ftz = [1.4846i 1.1582i];
P_pie=poly(ftz);%roots=ftz
jvals = -2:0.01:2;
for jidx = 1 : length(jvals)
j = jvals(jidx);
P_pie_subs(jidx)=polyval(P_pie,j*1i);
P_subs(jidx)=P_pie_subs(jidx)/(2*sqrt(2));
end
x=(-2:0.01:2);
x=x*1i;
P=polyfit(x,P_subs,2);
roots(P)
You forgot to take into account that binary floating point does not have an exact representation of 0.01, so your j values might not be exact multiples of 0.01 and floor() might get you a different index than you expect.