Comand window answer is wrong while the values in variable are ok. the x values in comand window is repeated and not in sequence

clear; clc;
xmin=-0.9;dx=.1;
fprintf('x ex\n')
fprintf('===============\n')
for i=1:19
x(i)=xmin+(i-1)*dx;
ex1(i)=(1+x(i)^2)^-0.5;
term=1;
for n=1:50
term(n+1)=-term(n)*(x(i)^2)*(2*n-1)/(2*n);
if abs(term(n+1))<=term(n)*1e-06
break;
end
end
ex(i)=sum(term);
fprintf(' %.2f %.6f %.6f \n',x,ex,ex1)
end

Answers (1)

You are printing the full arrays in your fprintf statement. You also forgot to pre-allocate your arrays, and you forgot to write comments.
clear; clc;
xmin=-0.9;dx=.1;
fprintf('x ex\n')
fprintf('===============\n')
x=zeros(1,19);
ex=zeros(1,19);
ex1=zeros(1,19);
for i=1:19
x(i)=xmin+(i-1)*dx;
ex1(i)=(1+x(i)^2)^-0.5;
term=zeros(1,50);term(1)=1;
for n=1:50
term(n+1)=-term(n)*(x(i)^2)*(2*n-1)/(2*n);
if abs(term(n+1))<=term(n)*1e-06
break;
end
end
ex(i)=sum(term);
fprintf(' %.2f %.6f %.6f \n',x(i),ex(i),ex1(i))
end

Categories

Find more on Signal Processing Toolbox in Help Center and File Exchange

Asked:

on 19 May 2020

Answered:

Rik
on 19 May 2020

Community Treasure Hunt

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

Start Hunting!