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

조회 수: 3 (최근 30일)
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

답변 (1개)

Rik
Rik 2020년 5월 19일
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

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by